Node root; publicTrie() { root = newNode(); } publicvoidinsert(String word) { Nodep= root; for (inti=0; i < word.length(); i++) { charcurr= word.charAt(i); intidx= curr - 'a'; if (p.charactersArr[idx] == null) p.charactersArr[idx] = newNode(); p = p.charactersArr[idx]; } p.isCompleteWord = true; } publicbooleansearch(String word) { Nodep= root; for (inti=0; i < word.length(); i++) { charcurr= word.charAt(i); intidx= curr - 'a'; if (p.charactersArr[idx] == null) returnfalse; p = p.charactersArr[idx]; } return p.isCompleteWord; } publicbooleanstartsWith(String prefix) { Nodep= root; for (inti=0; i < prefix.length(); i++) { charcurr= prefix.charAt(i); intidx= curr - 'a'; if (p.charactersArr[idx] == null) returnfalse; p = p.charactersArr[idx]; } 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); */