加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

字典树——add && find

发布时间:2020-12-14 01:53:15 所属栏目:Linux 来源:网络整理
导读:1 struct node{ 2 map char , struct node* children; 3 string word; 4 node(){ 5 word = "" ; 6 } 7 }; 8 class Trie{ 9 public : 10 struct node *root = NULL; 11 Trie(){ 12 root = new struct node(); 13 } 14 void addWord( string word){ 15 struct
 1 struct node{
 2     map<char,struct node*> children;
 3     string word;
 4     node(){
 5         word = "";
 6     }
 7 };
 8 class Trie{
 9     public:
10         struct node *root = NULL;
11         Trie(){
12             root = new struct node();
13         }
14         void addWord(string word){
15             struct node *cur = root;
16             for(int i = 0; i < word.length(); i++){
17                 if (cur->children.find(word[i]) == cur->children.end()) {
18                     cur->children[word[i]] = new struct node();
19                 }
20                 cur = cur->children[word[i]];
21             }
22             cur->word = word;
23         }
24         bool findWord(string word){
25             struct node *cur = root;
26             for(int i = 0; i < word.length(); i++){
27                 if(cur->children.find(word[i]) == cur->children.end()){
28                     return false;
29                 }
30                 cur = cur->children[word[i]];
31             }
32             return cur->word != "";
33         }
34 };

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读