#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int const N= 1000000;
struct Trie{
int id; // 标记每一个单词
int cnt; // 标记单词前缀的数量
int next[26]; // 26 个孩子结点
void init(){
id= 0; cnt= 0;
for( int i= 0; i< 26; ++i ) next= 0;
}
};
Trie tree[N];
int num= 0, root= 0, cid= 0;
void insert( char* s ){
int rt= root;
while( *s ){
int t= *s- 'a';
if( tree[rt].next[t]== 0 ){
tree[++num].init();
tree[rt].next[t]= num;
}
rt= tree[rt].next[t];
tree[rt].cnt++;
s++;
}
tree[rt].id= ++cid;
}
int find( char* s ){
int rt= root;
while( *s ){
int t= *s- 'a';
rt= tree[rt].next[t];
if( rt== 0 ) return 0;
s++;
}
return tree[rt].cnt;
}
int main(){
char str[100];
while( gets(str)!= NULL ){
if( strlen(str)== 0 ) break;
insert( str );
}
while( gets(str)!= NULL )
printf("%d\n", find(str) );
return 0;
}
Another implement: http://www.cnblogs.com/Xredman/archive/2009/04/10/1433167.html
本文介绍了一种使用Trie树的数据结构来实现字符串匹配的方法。通过初始化Trie树节点,插入字符串到Trie树中,并查找特定字符串的前缀数量。此外,还提供了一个可供参考的另一种实现方式。
2928

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



