Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Idea: It should be a dictionary tree.
1 classTrienode {2 Public:3Trienode *dic[ -];4 //Initialize your data structure here.5 Trienode () {6 for(inti =0; I < -; i++)7Dic[i] =NULL;8 }9 };Ten One classTrie { A Public: - Trie () { -Root =NewTrienode (); the } - - //inserts a word into the trie. - voidInsertstringword) { +trienode* cur =Root; - for(inti =0, Len = Word.size (); i < Len; i++) + { A intLOC = (int) (Word[i]-'a'); at if(Cur->dic[loc] = =NULL) -Cur->dic[loc] =NewTrienode (); -Cur = cur->Dic[loc]; - } - if(cur->dic[ -] ==NULL) -cur->dic[ -] =NewTrienode (); in } - to //Returns If the word is in the trie. + BOOLSearchstringword) { -trienode* cur =Root; the for(inti =0, Len = Word.size (); i < Len; i++) * { $ intLOC = (int) (Word[i]-'a');Panax Notoginseng if(Cur->dic[loc] = = NULL)return false; -Cur = cur->Dic[loc]; the } + if(cur->dic[ -] = = NULL)return false; A return true; the } + - //Returns If there is any word in the trie $ //That's starts with the given prefix. $ BOOLStartsWith (stringprefix) { -trienode* cur =Root; - for(inti =0, Len = Prefix.size (); i < Len; i++) the { - intLOC = (int) (Prefix[i]-'a');Wuyi if(Cur->dic[loc] = = NULL)return false; theCur = cur->Dic[loc]; - } 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");
Implement Trie (Prefix Tree)-Leetcode