Trie

经典题目

208 Implement Trie (Prefix Tree)

Trie:字典树。

  • Search:O(N)(N:word的长度)

  • Insert:O(N)(N:word的长度)

class Trie {
    class TrieNode {
        private TrieNode[] children;
        private boolean isEnd;
        public TrieNode() {
            this.children = new TrieNode[26];
        }
        public void put(char ch, TrieNode node) {
            children[ch - 'a'] = node;
        }
        public TrieNode get(char ch) {
            return children[ch - 'a'];
        }
        public void setEnd() {
            this.isEnd = true;
        }
        public boolean isEnd() {
            return isEnd;
        }
    }
    
    TrieNode root;
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        for(int i = 0; i < word.length(); i++) {
            char cur = word.charAt(i);
            if (node.get(cur) == null) {
                node.put(cur, new TrieNode());
            }
            node = node.get(cur);
        }
        node.isEnd = true;
    }
    
    /** Return the last TrieNode if the word is in the trie, otherwise return null */
    private TrieNode find(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            char cur = word.charAt(i);
            if (node.get(cur) == null) {
                return null;
            }
            node = node.get(cur);
        }
        return node;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = find(word);
        return node != null && node.isEnd();
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = find(prefix);
        return node != null;
    }
}

Last updated