Leetcode oj:implement Trie (Prefix Tree) (Implements a dictionary tree (prefix tree))

Source: Internet
Author: User

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))

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.