Sharing my fast Java solution


  • 0
    P

    The code remains almost same for all the 3 operations. Easy to remember the logic.

    class TrieNode{
            TrieNode[] children;
            boolean isLeaf;
            
            public TrieNode(){
                children = new TrieNode[26];
                isLeaf = false;
            }
        }
        
        TrieNode root;
    
        /** Initialize your data structure here. */
        public Trie() {
            this.root = new TrieNode();
        }
        
        /** Inserts a word into the trie. */
        public void insert(String word) {
            if(root == null) return;
            TrieNode current = root;
            for(char ch: word.toCharArray()){
                if(current.children[ch - 'a'] == null)
                    current.children[ch - 'a'] = new TrieNode();
                current = current.children[ch - 'a'];
            }
            current.isLeaf = true;
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            if(root == null) return false;
            TrieNode current = root;
            for(char ch: word.toCharArray()){
                if(current.children[ch - 'a'] == null)
                    return false;
                current = current.children[ch - 'a'];
            }
            if(!current.isLeaf)
                return false;
            return true;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            if(root == null) return false;
            TrieNode current = root;
            for(char ch: prefix.toCharArray()){
                if(current.children[ch - 'a'] == null)
                    return false;
                current = current.children[ch - 'a'];
            }
            return true;
        }
    

Log in to reply
 

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