classTrie{TrieNode root;publicTrie(){
root =newTrieNode('\0');// Insert dummy node as root}publicvoidinsert(String word){TrieNode currNode = root;// Iterate each character of the wordsfor(char c : word.toCharArray()){// Check if not existif(currNode.children[c -'a']==null){// Insert if the char is not present
currNode.children[c -'a']=newTrieNode(c);}// When exist switch to it and go on
currNode = currNode.children[c -'a'];}// Mark the last as the end of the word
currNode.isWord =true;}publicbooleansearch(String word){TrieNode currNode = root;for(char c : word.toCharArray()){// Check if not existif(currNode.children[c -'a']==null){returnfalse;}// Switch to the character and keep searching the next
currNode = currNode.children[c -'a'];}// Check the last character is the end of the wordreturn currNode.isWord ==true;}publicbooleanstartsWith(String prefix){TrieNode currNode = root;for(char c : prefix.toCharArray()){// Check if not existif(currNode.children[c -'a']==null){returnfalse;}// Switch to the character and keep searching the next
currNode = currNode.children[c -'a'];}returntrue;}classTrieNode{privatechar value;privateboolean isWord;privateTrieNode[] children;publicTrieNode(char val){this.value = val;this.isWord =false;this.children =newTrieNode[26];}}}