/** Initialize your data structure here. */ publicTrie() { root = newNode('#'); }
/** Inserts a word into the trie. */ publicvoidinsert(String word) { Nodecurrent= root; for (char ch : word.toCharArray()) { intindex= ch - 'a'; if (current.children[index] == null) { current.children[index] = newNode(ch); } current = current.children[index]; } current.isEnd = true; }
/** Returns if the word is in the trie. */ publicbooleansearch(String word) { Nodecurrent= root; for (char ch : word.toCharArray()) { intindex= ch - 'a'; if (current.children[index] == null) { returnfalse; } current = current.children[index]; }
return current.isEnd; }
/** Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix) { Nodecurrent= root; for (char ch : prefix.toCharArray()) { intindex= ch - 'a'; if (current.children[index] == null) { returnfalse; } current = current.children[index]; }
returntrue; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */