字典树算法入门解析

来源:互联网 发布:克隆mac地址有什么坏处 编辑:程序博客网 时间:2024/06/05 20:23

以下是百科的解释: 

字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高,下面是个百度来的字典树结构图

上面一个红点表示一个单词的尾部,分别表示abc,abcd,abd,bcd,b,efg,hii,如果我们要是查找这些单词中有没有abe,通过上图一看便知。

字典树的结构体:

struct node{int count;  //统计该单词出现多少次  struct node *next[26];  //代表26个字母 }
字典树构造:
for(i=0;i<len;i++){t=s[i]-'a';if(p->next[t]==NULL)p->next[t]=init();p=p->next[t];}p->count++; 
如果计算在abc,abc,abcd,abd,bcd,b,efg,hii中查找有没有或有几个abc,可以借字典树实现,下面给完整代码:
#include<stdio.h>#include<stdlib.h>#include<string.h>char str[8][10]={"abc","abc","abcd","abd","bcd","b","efg","hii"}; struct node{int count;struct node *next[26];};node *init(){node *p;p=(node*)malloc(sizeof(node));p->count=0;for(int i=0;i<26;i++)p->next[i]=NULL;return p;}void insert(node *root,char s[10]){int i,len,t;node *p=root;len=strlen(s);for(i=0;i<len;i++){t=s[i]-'a';if(p->next[t]==NULL)p->next[t]=init();p=p->next[t];}p->count++;}int query(node *root,char s[10]){int i,t,len;node *p=root;len=strlen(s);for(i=0;i<len;i++){t=s[i]-'a';if(p->next[t]==NULL)return 0;p=p->next[t];}return p->count;}int main(){char s1[10]="abc";node *root=init();for(int i=0;i<8;i++)insert(root,str[i]);int ans=query(root,s1);if(!ans)printf("没有该单词!\n");elseprintf("该单词有%d个\n",ans);}



原创粉丝点击