#include<stdio.h> //现在求的是 统计一个单词的前缀
//出现的次数,如果 把 注释部分 解注释 就会成为求 单词出现次数
#include<string.h>
#include<malloc.h>
typedef struct dictree
{
struct dictree *child[26]; // 26个指针对应 26 个字母
int n; // 统计字母出现的 次数
}DicTree
;
DicTree *root;
void insert(char *word)
{
DicTree *new_word,*temp;
int len=strlen(word);
if(len==0)return;
temp = root;
for(int i=0;i<len;i++)
{
if( temp->child[ word[i]-'a' ] !=0) //判断 原来 字典中是否存在 字母
{
temp = temp->child[word[i]-'a']; //存在 就判断下一个字母
// if(i==len-1) // 如果加上这个注释
//就会统计 最后出现的字母,就会成为统计单词 出现的次数
temp ->n= temp->n+1; //如果该 单词 出现过 ,n 就自加
}
else
{
new_word=(struct dictree *)malloc(sizeof(struct dictree));
for(int j=0;j<26;j++) //这里一定要是 26 千万别 写成 len了
new_word->child[j]=0;
temp->child[ word[i]-'a']=new_word;
temp=new_word;
// temp->n=0; //如果 统计单词的 个数 ,这里是初始化 0
// if(i==len-1)
temp->n=1; //新建一个出现次数为1
}
}
}
int find(char *word)
{
int len=strlen(word);
DicTree *find_word;
find_word=root;
for(int i=0;i<len;i++)
{
if(find_word->child[word[i]-'a']==0) //如果没有所要的结果就返回1
return 0;
find_word=find_word->child[word[i]-'a'];//否则继续执行下一个
}
return find_word->n;
}
int main()
{
char str[10];
root=(DicTree*)malloc(sizeof(DicTree));
for(int i=0;i<26;i++) //初始化
{
root->child[i]=0;
}
while(gets(str),strcmp(str,"")!=0) //这里要用 gets()
//才能达到结束的效果 结束为换行
insert(str);
while(scanf("%s",str)!=EOF)
{
int i=find(str);
printf("%d\n",i);
}
}