/** * Initialize your data structure here. */ publicTrie() { this.root = newTrieNode(); }
/** * Inserts a word into the trie. */ publicvoidinsert(String word) { TrieNodenode= root; for (inti=0; i < word.length(); i++) { intoffset= word.charAt(i) - 'a'; if (node.children[offset] == null) { node.children[offset] = newTrieNode(); } node = node.children[offset]; } node.end = true; }
/** * Returns if the word is in the trie. */ publicbooleansearch(String word) { TrieNodenode= getNodeByPrefix(word); return node != null && node.end; }
/** * Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix) { return getNodeByPrefix(prefix) != null; }