1 classTrienode {2 //Initialize your data structure here.3Trienode[] Children =NewTrienode[26];4 BooleanIsword;5 PublicTrienode () {6 }7 }8 9 Public classTrie {Ten PrivateTrienode Root; One A PublicTrie () { -Root =NewTrienode (); - } the - //inserts a word into the trie. - Public voidInsert (String word) { -Trienode current =Root; + for(inti = 0; I < word.length (); i++) { - if(Current.children[word.charat (i)-' a '] = =NULL) { +Current.children[word.charat (i)-' a '] =NewTrienode (); A } atCurrent = Current.children[word.charat (i)-' a ']; - } -Current.isword =true; - } - - //Returns If the word is in the trie. in Public BooleanSearch (String word) { -Trienode current =Root; to for(inti = 0; I < word.length (); i++) { + if(Current.children[word.charat (i)-' a '] = =NULL) { - return false; the } *Current = Current.children[word.charat (i)-' a ']; $ }Panax Notoginseng returnCurrent.isword; - } the + //Returns If there is any word in the trie A //That's starts with the given prefix. the Public BooleanstartsWith (String prefix) { +Trienode current =Root; - for(inti = 0; I < prefix.length (); i++) { $ if(Current.children[prefix.charat (i)-' a '] = =NULL) { $ return false; - } -Current = Current.children[prefix.charat (i)-' a ']; the } - return true;Wuyi } the } - Wu //Your Trie object would be instantiated and called as such: - //Trie Trie = new Trie (); About //Trie.insert ("somestring"); $ //trie.search ("key");
Implement Tries (Prefix Tree)