Java Easy Implementation, 18ms


  • 1
    S
    class TrieNode {
        public TrieNode[] next;
        
        public boolean isWord;
        // Initialize your data structure here.
        public TrieNode() {
            next = new TrieNode[26];
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            root = insert(root, word, 0);
        }
        
        private TrieNode insert(TrieNode node, String word, int depth) {
            if (node == null)  node = new TrieNode();
            if (depth == word.length()) {
                node.isWord = true;
                return node;
            }
            
            char c = word.charAt(depth);
            int index = c - 'a';
            node.next[index] = insert(node.next[index], word, depth + 1);
            return node;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
           TrieNode node = get(root, word, 0);
           return node != null && node.isWord;
        }
        
        private TrieNode get(TrieNode node, String word, int depth) {
            if (node == null) return null;
            else if (depth == word.length()) return node;
            
            char c = word.charAt(depth);
            return get(node.next[c - 'a'], word, depth + 1);
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
             return get(root, prefix, 0) != null;
        }
    }
    
    

Log in to reply
 

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