Java simple solution


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

Log in to reply
 

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