Implement a trie with insert
, search
, and startsWith
methods.
Implement the dictionary tree, the front seems to have done something similar to the problem, the code is as follows:
1 classTrienode {2 Public:3 //Initialize your data structure here.4Trienode (): IsLeaf (false)5 {6 for(Auto &t:dic) {7t =NULL;8 }9 }TenTrienode * dic[ -]; One BOOLisleaf; A }; - - classTrie { the Public: - Trie () { -Root =NewTrienode (); - } + - //inserts a word into the trie. + voidInsertstringword) { ATrienode * p =Root; at for(inti =0; I < word.size (); ++i) { - intindex = word[i]-'a'; - if(P->dic[index] = =NULL) -P->dic[index] =NewTrienode (); -p = p->Dic[index]; - } inP->isleaf =true; - } to + //Returns If the word is in the trie. - BOOLSearchstringword) { theTrienode * p =Root; * for(inti =0; I < word.size (); ++i) { $ intindex = word[i]-'a';Panax Notoginseng if(P->dic[index] = =NULL) - return false; thep = p->Dic[index]; + } A returnP->isleaf; the } + - //Returns If there is any word in the trie $ //That's starts with the given prefix. $ BOOLStartsWith (stringprefix) { -Trienode * p =Root; - for(inti =0; I < prefix.size (); ++i) { the intindex = prefix[i]-'a'; - if(P->dic[index] = =NULL)Wuyi return false; thep = p->Dic[index]; - } Wu return true; - } About $ Private: -trienode*Root; - }; - A //Your Trie object would be instantiated and called as such: + //Trie Trie; the //Trie.insert ("somestring"); - //trie.search ("key");
Leetcode oj:implement Trie (Prefix Tree) (Implements a dictionary tree (prefix tree))