数据结构 - trie

 1 #include <cstring>
 2 #include <iostream>
 3 #include <map>
 4 #include <cstdio>
 5 using namespace std;
 6 class Trie{
 7 private :
 8     map<char,Trie *> * root;
 9     pair<bool,int> info;
10     inline Trie * makeNext(char c){
11         if(root == NULL){
12             root = new map<char ,Trie * >;
13         }
14         map<char, Trie *>::iterator it  = root->find(c);
15         Trie * in ;
16         if( it ==  root->end()){
17             in = new Trie();
18             root->insert( pair<char , Trie * >(c,in));
19         }else{
20             in = it->second;
21         }
22         info.second ++ ;
23         return in;
24     }
25     inline void makeEnd(){
26         info.second ++ ;
27         info.first = true;
28     }
29     inline Trie * getChild(char c){
30         //该节点后面什么都没有了
31         if( root == NULL ){
32             return NULL;
33         }
34         map<char, Trie *>::iterator it  = root->find(c);
35         if(it == root->end()){
36             //有兄弟节点,但是没有这个后续
37             return NULL;
38         }
39         return it->second;
40     }
41     void destory(){
42         if(root != NULL){
43             for(map<char ,Trie *> :: iterator it = root->begin() ; it!=root->end() ; ++ it ){
44                 it->second->destory();
45             }
46             delete root;
47         }
48     }
49 public :
50     static pair<bool,int> None ;
51     Trie(){
52         root = NULL;
53         info = pair<bool,int>(false,0);
54     }
55     ~Trie(){
56         destory();
57     }
58     void addStr(char * str){
59         int len = strlen(str);
60         Trie * nowRoot = this;
61         while( (*str)!='\0'){
62             nowRoot = nowRoot->makeNext(*str);
63             ++str;
64         }
65         nowRoot->makeEnd();
66     }
67 
68     pair<bool,int> findStr(char * str){
69         Trie * nowRoot = this;
70         while((*str)!='\0'){
71             nowRoot = nowRoot->getChild(*str);
72             if( nowRoot == NULL){
73                 return None;
74             }
75             str++;
76         }
77         return nowRoot -> info;
78     }
79 };
80 pair<bool,int> Trie :: None = pair<bool,int>(false,-1);
81 int main(){
82     Trie * a = new Trie();
83     a->addStr("abcdfg");
84     a->addStr("abcd");
85     a->addStr("abc");
86     a->addStr("ab");
87     cout<<"stop "<<endl;
88     pair <bool,int> ans = a->findStr("abc");
89     cout<< ans.first << " " << ans.second<<endl;
90     delete a;
91     return 0;
92 }

 

posted @ 2016-10-25 11:08  默默无语敲代码  阅读(205)  评论(0编辑  收藏  举报