参考:https://blog.csdn.net/Dacc123/article/details/79771299
省略了一些头文件
1 #ifndef CHINESETRIETREE_H 2 #define CHINESETRIETREE_H 3 4 5 6 7 struct Node { 8 map<string,Node *> child; 9 int num; 10 int value; 11 Node(){ 12 num=0; 13 } 14 }; 15 16 class TrieTree{ 17 private: 18 Node *root; 19 int flag; 20 public: 21 TrieTree(){ 22 root=new Node(); 23 } 24 int insert(string s,int val){ 25 if(root==NULL||s=="")return -1; 26 int len=s.size(),i=0; 27 Node *p=root; 28 while(i<len){ 29 string sub=s.substr(i,i+3); 30 map<string,Node *>::iterator it= p->child.find(sub); 31 if(it==p->child.end()){ 32 Node *x=new Node(); 33 p->child.insert(make_pair(sub,x)); 34 p=x; 35 } else { 36 p->num++; 37 p=it->second; 38 } 39 i+=3; 40 } 41 p->value=val; 42 return val; 43 } 44 int find(string s){ 45 if(root==NULL||s=="")return -1; 46 int len=s.size(),i=0; 47 Node *p=root; 48 while(i<len){ 49 string sub=s.substr(i,i+3); 50 map<string,Node *>::iterator it= p->child.find(sub); 51 if(it==p->child.end()){ 52 return -1; 53 } else { 54 p=it->second; 55 } 56 i+=3; 57 } 58 return p->value; 59 } 60 }; 61 62 #endif