B.背单词 。。 KMP。模板题

大四了,Leyni感觉好惆怅,因为找不到工作,所以最后决定考研了,可是Leyni的英语好差,没办法,先从最基本的背单词开始吧。那么多单词怎么才好背呢,话说考研界盛传利用前缀背单词,貌似好神奇的样子。因为英语单词很多,Leyni想要知道以一个特定字符串做前缀的单词有多少,于是他来找你帮忙了。

Input
输入首先包含若干行小写单词,表示字典里的单词,以END结束,然后是若干个询问字符串,表示单词的前缀。输入到文件结束。最多不超过50000个单词。每个单词长度不超过15。
Output
对于每一个询问字符串,每行输出一个整数,表示单词表里有多少单词以此字符串作为前缀。
Sample Input
a
ab
aba
abcaa
END
aba
a
ab
abcd
Sample Output
1
4
3
0




#include<stdio.h>

#include<string.h>
struct trie{
    int cnt;
    trie *next[26];
};
trie *root=new trie;
void insert(char ch[]){
    trie *p=root,*newnode;
    for(int i=0;ch[i]!='\0';i++){
        if(p->next[ch[i]-'a']==0){
            newnode=new trie;
            for(int j=0;j!=26;j++){
                newnode->next[j]=NULL;
            }
            newnode->cnt=1;
            p->next[ch[i]-'a']=newnode;
            p=newnode;
        }else{
            p=p->next[ch[i]-'a'];
            p->cnt++;
        }
    }
}
int find(char ch[]){
    trie *p=root;
    for(int i=0;ch[i]!='\0';i++){
        if(p->next[ch[i]-'a']!=NULL)
            p=p->next[ch[i]-'a'];
        else
            return 0;
    }
    return p->cnt;
}
int main(){
    char ch[20];
    for(int i=0;i!=26;i++){
        root->next[i]=NULL;
    }
    root->cnt=0;
    while(gets(ch)){//±ØÐëÓÃgets
        if(!strcmp(ch,"END")) break;
        insert(ch);
    }
    while(scanf("%s",ch)!=EOF){
        printf("%d\n",find(ch));
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值