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