学习 字典树

#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);
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值