阅读 50

leetcode208 前缀树

其实就是一个用于存储字符的多叉树,每一个节点代表一个字符。每个节点还维护一个bool变量用于判断是否为某一字符串的结尾。通过数组实现,贴代码

 1 class Trie {
 2 public:
 3     vector children;
 4     bool isEnd;
 5 
 6     /** Initialize your data structure here. */
 7     Trie():children(26),isEnd(false)
 8     {
 9     }
10     
11     /** Inserts a word into the trie. */
12     void insert(string word) 
13     {
14         Trie* node = this;
15         for(auto temp:word)
16         {
17             temp -= a;
18             if(node->children[temp] == nullptr)
19             {
20                 node->children[temp] = new Trie();
21             }
22             node = node->children[temp];
23         }
24         node->isEnd = true;
25     }
26     
27     /** Returns if the word is in the trie. */
28     bool search(string word) 
29     {
30         Trie* node = this;
31         for(auto temp:word)
32         {
33             temp -= a;
34             if(node->children[temp] != nullptr)
35             node = node->children[temp];
36             else
37             return false;
38         }
39         if(node->isEnd)
40         return true;
41         else
42         return false;        
43     }
44     
45     /** Returns if there is any word in the trie that starts with the given prefix. */
46     bool startsWith(string prefix) 
47     {
48         Trie* node = this;
49         for(auto temp:prefix)
50         {
51             temp -= a;
52             if(node->children[temp] != nullptr)
53             node = node->children[temp];
54             else
55             return false;
56         }
57         return true;
58     }
59 };
60 
61 /**
62  * Your Trie object will be instantiated and called as such:
63  * Trie* obj = new Trie();
64  * obj->insert(word);
65  * bool param_2 = obj->search(word);
66  * bool param_3 = obj->startsWith(prefix);
67  */

 

原文:https://www.cnblogs.com/zhaohhhh/p/15305301.html

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐