Damn simple trie impl with array


  • 0
    Z
    class TrieNode {
        boolean hasValue = false;
        TrieNode[] subs = new TrieNode[26];
        
        // Initialize your data structure here.
        public TrieNode() {}
    }
    
    public class Trie {
        /*root should not contain any char.*/
        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()){
                if(node.subs[c-'a'] == null){
                    node.subs[c-'a'] = new TrieNode();
                }
                
                node = node.subs[c-'a'];
            }
            
            node.hasValue = true;
        }
    
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode node = find(word);
            return node!= null && node.hasValue;
        }
    
        // 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;
        }
        
        // return the node found while going down with this key
        private TrieNode find(String key){
            TrieNode node = root;
            for(char c: key.toCharArray()){
                node = node.subs[c-'a'];
                if(node == null)
                    return null;
            }
            
            return node;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.