An intuitive solution 15ms 95%


  • 0
    L
    class TrieNode {
        TrieNode[] children;
        boolean isWord;
        // can add other class variable here if needed
        // depends on application
        
        public TrieNode() {
            children = new TrieNode[26];
            isWord = false;
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode p = root;
            for (char ch : word.toCharArray()) {
                if (p.children[ch - 'a'] == null) {
                    p.children[ch - 'a'] = new TrieNode();
                }
                p = p.children[ch - 'a'];
            }
            p.isWord = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode p = root;
            for (char ch : word.toCharArray()) {
                if (p.children[ch - 'a'] != null) {
                    p = p.children[ch - 'a'];
                } else {
                    return false;
                }
            }
            return p.isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode p = root;
            for (char ch : prefix.toCharArray()) {
                if (p.children[ch - 'a'] != null) {
                    p = p.children[ch - 'a'];
                } else {
                    return false;
                }
            }
            return true;
        }
    }

Log in to reply
 

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