hdu 1251 字典树 求前缀有多少个
做的第一个字典树,非常直观
第一类是求前缀有多少个,第二类是求前缀是否在一串字符中出现
主要是字典树的构造,使用了一个嵌套的结构体,使用了指针,非常方便
也非常巧妙,还有就是root,newnode必须初始空间
banana
band
bee
absolute
acm
ba
b
band
abc
#include <stdio.h> #include <string.h> #include <malloc.h> struct dictree { dictree *child[26]; int n; }; struct dictree *root; void insert(char *str) { struct dictree *current,*newnode; int len=strlen(str); current=root; for(int i=0;i<len;i++) { if(current->child[str[i]-'a']!=0) { current=current->child[str[i]-'a']; current->n=current->n+1; }else { newnode=(struct dictree*)malloc(sizeof(struct dictree)); for(int j=0;j<26;j++) newnode->child[j]=0; current->child[str[i]-'a']=newnode; current=newnode; current->n=1; } } } int find(char *str) { struct dictree *current; int len=strlen(str); int i; if(len==0)return 0; current=root; for(i=0;i<len;i++) { if(current->child[str[i]-'a']!=0) current=current->child[str[i]-'a']; else return 0; } return current->n; } int main() { char strs[11]; int i; root=(struct dictree*)malloc(sizeof(struct dictree)); for(i=0;i<26;i++) root->child[i]=0; root->n=2; while(gets(strs),strcmp(strs,"")!=0) insert(strs); while(scanf("%s",strs)!=EOF) { printf("%d\n",find(strs)); } return 0; }