【前缀树】208. 实现 Trie (前缀树)

题目:

 

 

解答:

 1 class Trie {
 2 private:
 3     bool isEnd;
 4     Trie* next[26];
 5 public:
 6     Trie() 
 7     {
 8         isEnd = false;
 9         memset(next, 0, sizeof(next));
10     }
11     
12     void insert(string word) 
13     {
14         Trie* node = this;
15         for (char c : word) 
16         {
17             if (node->next[c-'a'] == NULL) 
18             {
19                 node->next[c-'a'] = new Trie();
20             }
21             node = node->next[c-'a'];
22         }
23         node->isEnd = true;
24     }
25     
26     bool search(string word) 
27     {
28         Trie* node = this;
29         for (char c : word) 
30         {
31             node = node->next[c - 'a'];
32             if (node == NULL) 
33             {
34                 return false;
35             }
36         }
37         return node->isEnd;
38     }
39     
40     bool startsWith(string prefix)
41     {
42         Trie* node = this;
43         for (char c : prefix) 
44         {
45             node = node->next[c-'a'];
46             if (node == NULL) 
47             {
48                 return false;
49             }
50         }
51         return true;
52     }
53 };

 

posted @ 2020-05-05 21:44  梦醒潇湘  阅读(186)  评论(0)    收藏  举报