1 classTrienode {2 Public:3 Const Static intNr_fanout = -;4trienode*Child[nr_fanout];5 intcount;6 //Initialize your data structure here.7 Trienode () {8 for(intI=0; i<nr_fanout; i++) {9Child[i] =NULL;Ten } OneCount =0; A } - }; - the classTrie { - Public: - Trie () { -Root =NewTrienode (); + } - + //inserts a word into the trie. A voidInsertstrings) { atInsert (S,0, root); - } - - //Returns If the word is in the trie. - BOOLSearchstringkey) { - returnSearch (Key,0, root)! =NULL; in } - to //Returns If there is any word in the trie + //That's starts with the given prefix. - BOOLStartsWith (stringprefix) { the returnSearch_prefix (prefix,0, root)! =NULL; * } $ Private:Panax Notoginsengtrienode* Insert (string& S,intPOS, trienode*Current ) { - intLen =s.size (); the if(Pos >Len) { + returnNULL; A } the if(Current = =NULL) { +Current =NewTrienode (); - } $ if(pos = =Len) { $current->count++; - returnCurrent ; - } the intIDX = S[pos]-'a'; -CURRENT->CHILD[IDX] = insert (s, POS +1, current->Child[idx]);Wuyi returnCurrent ; the } - WuTrienode* Search (string& S,intPOS, trienode*Current ) { - if(Current = =NULL) { About returnNULL; $ } - intLen =s.size (); - if(Pos >Len) { - returnNULL; A}Else if(pos = = Len && current->count) { + returnCurrent ; the } - returnSearch (s, pos +1, Current->child[s[pos]-'a']); $ } thetrienode* Search_prefix (string& S,intPOS, trienode*Current ) { the if(Current = =NULL) { the returnNULL; the } - intLen =s.size (); in if(Pos >=Len) { the returnCurrent ; the } About returnSearch_prefix (s, POS +1, Current->child[s[pos]-'a']); the } the Private: thetrienode*Root; +};
Mplement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Leetcode Tries Prefix Tree