美文网首页
208. 实现 Trie (前缀树)

208. 实现 Trie (前缀树)

作者: justonemoretry | 来源:发表于2021-09-01 22:23 被阅读0次
image.png

解法

class Trie {

    private Trie[] children;
    private boolean isEnd;

    /** Initialize your data structure here. */
    public Trie() {
        // 26个字母,26叉树
        children = new Trie[26];
        // 判断这个节点有没有字符串结束
        isEnd = false;
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            // 节点不存在,则在对应节点初始化
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie node = searchTrie(word);
        return node != null && node.isEnd == true;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        return searchTrie(prefix) != null;
    }

    /**
     * 统一查找,找不到就返回null
     */
    private Trie searchTrie(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            int index = prefix.charAt(i) - 'a';
            if (node.children[index] == null) {
                return null;
            }   
            node = node.children[index];
        }
        return node;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

相关文章

网友评论

      本文标题:208. 实现 Trie (前缀树)

      本文链接:https://www.haomeiwen.com/subject/aicailtx.html