字典树(trie)
2012-11-12 17:02
225 查看
#include<iostream> #include<vector> #include<string> using namespace std; #define MAXSIZE 10 typedef struct trie { char *data; struct trie *next[26]; trie():data(NULL) { for(int k=0;k<26;k++) next[k]=NULL; } }TRIE; TRIE *trie; void print(TRIE *root) { if(!root) return; if(root->data!=NULL) cout<<root->data<<endl; for(int i=0;i<26;i++) print(root->next[i]); } void free_node(TRIE *root) { if(root==NULL) return; for(int i=0;i<26;i++) { trie=root->next[i]; free_node(trie); if(trie!=NULL&&trie->data!=NULL) { delete trie->data; trie=NULL; } } } void free_trie(TRIE *root) { free_node(root); if(root->data!=NULL) delete root->data; } void insert(TRIE * &root,char *str,const char *data) { if(!root) return; TRIE *trie = root; char *cur=str; int i; while(*cur) { if(*cur>='A'&&*cur<='Z') i=*cur-'A'; else if(*cur>='a'&&*cur<='z') i=*cur-'a'; if(!trie->next[i]) { trie->next[i]=new TRIE(); } cur++; trie=trie->next[i]; } trie->data=new char(strlen(data)+1); strcpy(trie->data,data); } int search(TRIE *root,char *str,char *result) { char *cur=str; int i,j; while(*cur) { if(*cur>='A'&&*cur<='Z') i=*cur-'A'; else if(*cur>='a'&&*cur<='z') i=*cur-'a'; if(root->next[i]==NULL) { strcpy(result,""); return 0; } cur++; root=root->next[i]; } strcpy(result,root->data); return 1; } int main() { TRIE *root; root=new TRIE(); insert(root,"Alexander-china","this is Alexander-china!"); insert(root,"zhang san","this is zhang san!"); insert(root,"li si","this is li si!"); // print(root); char result[200]; search(root,"Alexander-china",result); cout<<result<<endl; search(root,"zhang san",result); cout<<result<<endl; search(root,"li si",result); cout<<result<<endl; free_trie(root); system("pause"); return 1; }
相关文章推荐
- zju2346 Shortest Prefixes(字典树 trie)
- Trie[字典树] 数据结构及基本操作集
- Trie(字典树)
- 字典树(Trie)
- Data Structure: Trie(字典树)
- 字典树Trie
- POJ 2503 Babelfish(字典树Trie)
- zoj 3228 trie tree(字典树)
- HDU 1671 Phone List(字典树Trie)
- LeetCode211. Add and Search Word - Data structure design前缀树(Trie,字典树)实战
- HDU5687(字典树Trie增删查)
- 详解字典树Trie结构及其Python代码实现
- Trie(字典树)学习小结1
- 用KMP算法与Trie字典树实现屏蔽敏感词(UTF-8编码)
- 字典树trie_tree
- 【算法】Trie数(前缀树/字典树)简介及Leetcode上关于前缀树的题
- (字典树Trie Tree)HDU 1251 统计难题
- Data Structure: Trie(字典树)
- HDU-1305 Immediate Decodability (Trie 字典树 入门题)
- Trie 树(又称字典树,单词查找树)