题意:统计一某个单词为前缀的单词的数量。
思路:简单的字典树。
字典树的操作就三个一个是初始化,一个是插入建树,另一个查找。
统计前缀的数量,每读入一个单词,像树的深度遍历一样一层一层,如果节点存在该节点的出现次数+1,如果该节点没有出现,则申请一个空间,初始化该点,继续搜索
单词的查找,就是树的深度遍历,找到后输出他的出现次数
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct Trie
{
struct Trie * child[26];
int n;
};
struct Trie * root;
void insert(char * str)
{
int i,j,len;
len = strlen(str);
struct Trie * node,*tnode;
node = root;
if(len == 0)
return ;
for(i = 0; i < len; i++)
{
if(node -> child[str[i]-'a'] != NULL)
{
node = node -> child[str[i]-'a'];
node -> n = node -> n + 1;
}
else
{
tnode = (struct Trie*)malloc(sizeof(struct Trie));
for(j = 0; j < 26; j++)
{
tnode -> child[j] = NULL;
}
node -> child[str[i]-'a'] = tnode;
node = tnode;
node -> n = 1;
}
}
}
int find(char* str)
{
int i,len;
struct Trie * node;
node = root;
len = strlen(str);
if(len == 0)
return 0;
for(i = 0;i < len; i++)
{
if(node -> child[str[i]-'a'] != NULL)
{
node = node -> child[str[i]-'a'];
}
else
return 0;
}
return node -> n;
}
int main()
{
char s[1000];
int i;
root = (struct Trie*)malloc(sizeof(struct Trie));
for(i = 0; i < 26; i++)
root -> child[i] = NULL;
//root -> n = 2;
while(gets(s))
{
if(s[0] == '\0')
break;
else
{
insert(s);
}
}
while(scanf("%s",s) != EOF)
{
printf("%d\n",find(s));
}
return 0;
}