Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume this all inputs is consist of lowercase letters a-z
.
Analyse:for each node, it has a children, from a-Z.
1. For the string insertion operation, the procedure is:
--set Root as the temp node;
--for every character in the string, compute it corresponding place at the branch, and mark them.
--after all characters is marked, set Isval to indicate it ' s a value rather than a prefix.
2. For the search operation, the procedure is:
--set Root as the temp node;
--for every character in the string, continuously check the existance of it. If NULL node encountered, jump out the of loop.
--if the node is empty and then return false; Else, we need to judge whether this string is a value or a prefix.
3. For the startwith operation, it's quite similiar to the search operation except this all search operations with true re Sult returned can return true in the start operation.
Runtime:64ms.
1 classTrienode {2 Public:3 //Initialize your data structure here.4trienode* childnode[ -];5 BOOLIsval;//To indicate whether the leaf node is the target word or the prefix6 Trienode () {7Isval =false;8 for(inti =0; I < -; i++)9Childnode[i] =NULL;Ten } One }; A - classTrie { - Public: the Trie () { -Root =NewTrienode (); - } - + //inserts a word into the trie. - voidInsertstringword) { +trienode* temp =Root; A for(inti =0; I < word.size (); i++){ at if(Temp->childnode[word[i]-'a'] ==NULL) -Temp->childnode[word[i]-'a'] =NewTrienode (); -temp = Temp->childnode[word[i]-'a']; - } -Temp->isval =true;//if the word is inserted, then Isval is true - } in - //Returns If the word is in the trie. to BOOLSearchstringword) { +trienode* temp =Root; - for(inti =0; I < word.size (); i++){ the if(temp = = NULL) Break; *temp = Temp->childnode[word[i]-'a']; $ }Panax Notoginseng if(!temp)return false;//If the route does not exist, return false - returnTemp->Isval; the } + A //Returns If there is any word in the trie the //That's starts with the given prefix. + BOOLStartsWith (stringprefix) { -trienode* temp =Root; $ for(inti =0; I < prefix.size (); i++){ $ if(temp = = NULL) Break; -temp = Temp->childnode[prefix[i]-'a']; - } the if(temp) - return true;//if it ' s the leaf node, return trueWuyi Else the return false;//if it ' s not the leaf node, return false; - } Wu - Private: Abouttrienode*Root; $ }; - - //Your Trie object would be instantiated and called as such: - //Trie Trie; A //Trie.insert ("somestring"); + //trie.search ("key");
Implement Trie (Prefix Tree)