题目要求统计出以某个字符串为前缀的单词数量,字典树入门模板题。
AC code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
const int maxn = 1e4 + 10;
struct node{
int cnt;
node* nex[26];
node(){
cnt = 0;
memset(nex,0,sizeof(nex));
}
}root;
void insert(char *s){
node* p = &root;
int len = strlen(s);
for(int i = 0;i < len;++i){
if(p->nex[s[i] - 'a'] == NULL){
node* tmp = new node;
p->nex[s[i] - 'a'] = tmp;
}
p = p->nex[s[i] - 'a'];
++p->cnt;
}
}
int search(char *s){
node* p = &root;
int len = strlen(s);
for(int i = 0;i < len;++i){
if(p->nex[s[i] - 'a'] == NULL){
//printf("9\n");
return 0;
}
p = p->nex[s[i] - 'a'];
}
//printf("%d\n",p->cnt);
return p->cnt;
}
void del(node* root){
for(int i = 0;i < 10;++i){
if(root->nex[i]){
del(root->nex[i]);
}
}
del(root);
}
int main(){
char str[12];
//while(gets(str) && strcmp(str,"") != 0){
while(gets(str) && str[0] != '\0'){//使用gets读取空行
insert(str);
}
while(scanf("%s",str) != EOF){
printf("%d\n",search(str));
}
//del(&root);//不注释掉会超时
return 0;
}