LeetCode achieve Trie (Prefix Tree)

Topic links: https://leetcode-cn.com/problems/implement-trie-prefix-tree/

Subject to the effect:

  slightly.

analysis:

  Trie template.

code show as below:

. 1  class Trie {
 2  public :
 . 3      int passed; // record the number of strings through this node 
. 4      int ends;    // record the number of this string ending node 
. 5      unordered_map < char , Trie *> NXT;
 . 6      
. 7      / * . * Data Structure your here Wallpaper the Initialize * / 
. 8      Trie () {
 . 9          passed = 0 ;
 10          ends = 0 ;
 . 11      }
 12 is      
13 is      / * * Inserts Number INTO A Word The Trie. * / 
14     void insert(string word) {
15         Trie* p = this;
16         for(int i = 0; i < word.size(); ++i) {
17             if(p->nxt.find(word[i]) == p->nxt.end()) {
18                 p->nxt[word[i]] = new Trie();
19             }
20             ++p->passed;
21             p = p->nxt[word[i]];
22         }
23         ++p->ends;
24     }
25     
26     /** Returns if the word is in the trie. */
27     bool search(string word) {
28         Trie* p = this;
29         for(int i = 0; i < word.size(); ++i) {
30             if(p->nxt.find(word[i]) == p->nxt.end()) return false;
31             p = p->nxt[word[i]];
32         }
33         return p->ends != 0;
34     }
35     
36     /** Returns if there is any word in the trie that starts with the given prefix. */
37     bool startsWith(string prefix) {
38         Trie* p = this;
39         for(int i = 0; i < prefix.size(); ++i) {
40             if(p->nxt.find(prefix[i]) == p->nxt.end()) return false;
41             p = p->nxt[prefix[i]];
42         }
43         return true;
44     }
45 };
46 
47 /**
48  * Your Trie object will be instantiated and called as such:
49  * Trie* obj = new Trie();
50  * obj->insert(word);
51  * bool param_2 = obj->search(word);
52  * bool param_3 = obj->startsWith(prefix);
53  */
View Code

 

Guess you like

Origin www.cnblogs.com/zaq19970105/p/11457612.html
Recommended