字典树模板

来源:互联网 发布:怎么在知乎回答问题 编辑:程序博客网 时间:2024/06/03 16:40

字典树

 
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
//字典树模板#include <stdio.h>#include <iostream>#include <stdlib.h>#define MAX 26using namespace std;typedef struct TrieNode{bool isStr;                          //标记该节点处是否构成单词struct TrieNode *next[MAX];          //儿子分支}Trie;//建树void insert(Trie *root, const char *s){if(root==NULL || *s=='\0')return;Trie *p = root;p->isStr = false;while(*s!='\0'){if(p->next[*s-'a']==NULL)      //不在树中{Trie *temp = (Trie *)malloc(sizeof(Trie));temp->isStr = false;for(int i=0; i<MAX; i++) temp->next[i] = NULL;p->next[*s - 'a'] = temp;p = temp;}else{p = p->next[*s - 'a'];}s++;}p->isStr = true;            //最末尾标记为有这个单词}//查询bool reach(Trie *root, char *s){Trie *q = root;while(q!=NULL && *s!='\0'){q = q->next[*s-'a'];s++;}if(q!=NULL && q->isStr)return true;return false;}//释放空间void del(Trie *root){if(root!=NULL){for(int i=0; i<MAX; i++){if(root->next[i]!=NULL)del(root->next[i]);}free(root);}}int main(){int n;Trie *t = (Trie *)malloc(sizeof(Trie));for(int i=0; i<MAX; i++)t->next[i] = NULL;scanf("%d", &n);//建立字典树for(int i=0; i<n; i++){char s[105];scanf("%s", s);insert(t, s);}int m;scanf("%d", &m);//m次查找while(m--){char s[105];scanf("%s", s);if(reach(t, s))            printf("%s 存在\n", s);        else            printf("%s 不存在\n", s);}del(t);              //释放空间return 0;}


原创粉丝点击