华为常考-前缀树-字典树-请五分钟写出来


class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

#23届找工作求助阵地#
全部评论
给我500分钟
1 回复 分享
发布于 2023-05-04 11:02 浙江
node = node.children[index];
1 回复 分享
发布于 2023-03-25 00:09 日本
五分钟写出来对我难度太大。。。
点赞 回复 分享
发布于 2023-03-25 13:12 浙江

相关推荐

熊大不大:微信也是华为旗下吧,我看我朋友也是华为工牌写wx
点赞 评论 收藏
分享
评论
7
15
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务