首页 > 其他 > 详细

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

时间:2020-05-05 23:07:28      阅读:75      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

 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 };

 

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

原文:https://www.cnblogs.com/ocpc/p/12833042.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!