10k

208. Implement Trie (Prefix Tree)

问题

实现一个trie

算法

关于trie是什么以及作用,以及优缺点和实现,请参阅我早些的博文: A quick Node of Trie.

代码

class Trie {
    
    TrieNode root;
    
    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode curNode = root;
        for (Character c : word.toCharArray()) {
            if (curNode.children[c-'a'] == null) {
                curNode.children[c-'a'] = new TrieNode();
            }
            curNode = curNode.children[c-'a'];
        }
        curNode.isWord = true;
    }
    
    public boolean search(String word) {
        TrieNode curNode = root;
        for (Character c : word.toCharArray()) {
            if (curNode.children[c-'a'] == null) {
                return false;
            }
            curNode = curNode.children[c-'a'];
        }
        return curNode.isWord;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode curNode = root;
        for (Character c : prefix.toCharArray()) {
            if (curNode.children[c-'a'] == null) {
                return false;
            }
            curNode = curNode.children[c-'a'];
        }
        return true;
    }
    
    class TrieNode {
        boolean isWord;
        TrieNode[] children;
        public TrieNode() {
            children = new TrieNode[26];
        }
    }
}

/**
 * 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);
 */
Thoughts? Leave a comment