Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Because of the 26-letter array, you don't even have to save Val on Trienode.
1 classTrienode {2 //Initialize your data structure here.3 Boolean Isword;4 trienode[] Children;5 6 PublicTrienode () {7 This. Isword =false;8Children =NewTrienode[26];9 }Ten } One A Public classTrie { - PrivateTrienode Root; - the PublicTrie () { -Root =NewTrienode (); - } - + //inserts a word into the trie. - Public voidInsert (String word) { +Trienode cur =Root; A for(inti = 0; I < word.length (); i + +){ atCharacter C =Word.charat (i); - if(Cur.children[c-' a '] = =NULL){ -Trienode tmp =NewTrienode (); -Cur.children[c-' a '] =tmp; - } -cur = cur.children[c-' a ']; in } -Cur.isword =true; to } + - Privatetrienode FindNode (String word) { theTrienode cur =Root; * for(inti = 0; I < word.length (); i + +){ $Character C =Word.charat (i);Panax Notoginseng if(Cur.children[c-' a '] = =NULL){ - return NULL; the } +cur = cur.children[c-' a ']; A } the returncur; + } - $ //Returns If the word is in the trie. $ Public BooleanSearch (String word) { -Trienode end =FindNode (word); - returnEnd! =NULL&&End.isword; the } - Wuyi //Returns If there is any word in the trie the //That's starts with the given prefix. - Public BooleanstartsWith (String prefix) { Wu returnFindNode (prefix)! =NULL; - } About } $ - //Your Trie object would be instantiated and called as such: - //Trie Trie = new Trie (); - //Trie.insert ("somestring"); A //trie.search ("key");
Implement Trie (Prefix Tree)