208. Implement Trie (Prefix Tree)

time: O(n), n is word len

space: O(26*n), each node have 26 chars, in worst case, tire will have n level , n is word len

class Trie {
    
    class TrieNode {
        Map<Character, TrieNode> sons;
        boolean isWord;
        String word;
        TrieNode() {
            this.sons = new HashMap<>();
            this.isWord = false;
            this.word = null;
        }
    }

    /** Initialize your data structure here. */
    private TrieNode root;
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            node.sons.computeIfAbsent(c, k -> new TrieNode());
            node = node.sons.get(c);
        }
        node.isWord = true;
        node.word = word;
    }
    
    private TrieNode getNode(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            TrieNode next = node.sons.get(c);
            if (next == null) {
                return null;
            }
            node = next;
        }
        return node;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = getNode(word);
        return node != null && node.isWord;
    }
    
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    // ex: build: apple
    // input prefix: app (prefix 比較短
    // so getNode will return a node is going to app's last p, so next not null!
    public boolean startsWith(String prefix) { 
        TrieNode node = getNode(prefix);
        return node != null;
    }
}

/**
 * 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);
 */

Last updated