题目链接:hdu 1251
解法:构造一个字典树,根据给出模式串统计字典树上的结点分别被多少个单词覆盖到,统计到的某结点的ch值便是以该结点结尾的字符串为前缀的单词个数。
代码如下:
#include <cstdio>
#include <cstring>
struct trie
{
trie *next[26]; // 假设只有26个小写字母
int ch; // 统计有多少个单词覆盖到当前结点
trie() { // 用于初始化的构造函数
memset(next, 0, sizeof(next));
ch = 1;
}
} *root;
void insert(char *s)
{
trie *p = root;
while(*s) {
int index = *s - 'a';
if(p->next[index]) p->next[index]->ch++;
else p->next[index] = new trie;
p = p->next[index];
s++;
}
}
int search(char *s)
{
trie *p = root;
while(*s) {
int index = *s - 'a';
if(!p->next[index]) return 0;
p = p->next[index];
s++;
}
return p->ch;
}
int main()
{
root = new trie;
char s[15];
while(gets(s), s[0] != '\0') insert(s);
while(gets(s)) printf("%d\n", search(s));
return 0;
}
本文介绍了一种利用字典树进行高效模式匹配的方法。通过构建字典树并统计节点覆盖情况,可以快速查找字符串前缀对应的单词数量。文中提供了完整的C++实现代码。
1043

被折叠的 条评论
为什么被折叠?



