字典树:
用于统计、排序和保存大量的字符串,它的优点是节约了存储空间,并且查找的效率很高。
题意:
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
思路:用字典树存储单词表,在建树的过程中就记录该单词出现的次数,然后查询的时候,直接输出对应的单词的次数就行了。比如样例中单词表为”banana band bee absolute acm”,这样的话,’b’出现的次数就是3次,’ba’出现的次数就是2次。
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstring>
#include <malloc.h>
struct Trie
{
Trie *next[26];
int num;
};
void Init(Trie *t) //初始化结点
{
t->num = 0;
for(int i = 0; i < 26; i++)
{
t->next[i] = NULL;
}
}
void Insert(Trie *root, char s[])
{
Trie *t = root;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(t->next[s[i]-'a'] == NULL) //如果该结点为出现过,那就新加一个分支
{
t->next[s[i]-'a'] = (Trie *)malloc(sizeof(Trie));
Init(t->next[s[i]-'a']);
}
t = t->next[s[i] - 'a']; //指向孩子结点
t->num++; //次数加一
}
}
int Query(Trie *root, char s[]) //查找字符串
{
Trie *t = root;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(t->next[s[i]-'a'] == NULL) //没有该字符串,返回0,证明出现次数为0次
return 0;
t = t->next[s[i]-'a'];
}
return t->num; //匹配完成,返回出现次数
}
int main()
{
char a[30];
Trie *root = (Trie*)malloc(sizeof(Trie));
Init(root);
while(gets(a) && a[0])
{
Insert(root, a);
}
while(gets(a))
{
printf("%d\n", Query(root, a));
}
return 0;
}