The structure of the standard trie is
1 class Trienode {2 trienode[] child; 3 Char Curchar; 4 Hashset<integer> HashSet; 5 int freq; 6 }
But we don't need Freq or hashset in this question, but to show that the current node is not the end of a word, we set a Boolean isleaf.
The reason for doing this is to consider the following two scenarios:
1. If you insert AB, but search for a, you should return false, search prefix should return true
2. Insert AB,ABC, search AB should return true, searching prefix AB should also return true
So we're going to record if it's the end.
1 classTrienode {2 //Initialize your data structure here.3 Publictrienode[] Children;4 Public CharCurchar;5 Public Booleanisleaf;6 7 PublicTrienode () {8Children =NewTrienode[26];9IsLeaf =false;Ten } One } A - Public classTrie { - PrivateTrienode Root; the - PublicTrie () { -Root =NewTrienode (); - } + - //inserts a word into the trie. + Public voidInsert (String word) { A intLen =word.length (); at if(len = = 0) { - return; - } -Trienode Curnode =Root; - for(inti = 0; i < Len; i++) { - CharCur =Word.charat (i); in intindex = cur-' a '; - if(Curnode.children[index] = =NULL) { toCurnode.children[index] =NewTrienode (); +Curnode.children[index].curchar =cur; - } theCurnode =Curnode.children[index]; * } $Curnode.isleaf =true;Panax Notoginseng } - the //Returns If the word is in the trie. + Public BooleanSearch (String word) { A if(word.length () = = 0) { the return true; + } -Trienode Curnode =Root; $ for(inti = 0; I < word.length (); i++) { $ CharCur =Word.charat (i); - intindex = cur-' a '; - if(Curnode.children[index] = =NULL) { the return false; - }WuyiCurnode =Curnode.children[index]; the } - returncurnode.isleaf; Wu } - About //Returns If there is any word in the trie $ //That's starts with the given prefix. - Public BooleanstartsWith (String prefix) { - if(prefix.length () = = 0) { - return true; A } +Trienode Curnode =Root; the for(inti = 0; I < prefix.length (); i++) { - CharCur =Prefix.charat (i); $ intindex = cur-' a '; the if(Curnode.children[index] = =NULL) { the return false; the } the if(Curnode.children[index].curchar! =cur) { - return false; in } theCurnode =Curnode.children[index]; the } About return true; the } the } the + //Your Trie object would be instantiated and called as such: - //Trie Trie = new Trie (); the //Trie.insert ("somestring");Bayi //trie.search ("key");
208. Implement Trie (Prefix Tree)