简单的字典树题,首先简历字典树,在查找。
#include<iostream>
using namespace std;
struct Tri
{
int v;
Tri* child[26];
} root;
void Init()
{
root.v=0;
for(int i=0;i<26;i++)
{
root.child[i]=NULL;
}
}
void CreateDic(char* str)
{
Tri* p;
int j;
p=&root;
while(*str!=NULL)
{
if(p->child[*str-'a']==NULL)
{
p->child[*str-'a']=(Tri*)new Tri;
p->child[*str-'a']->v=1;
for(j=0;j<26;j++)
p->child[*str-'a']->child[j]=NULL;
}
else
p->child[*str-'a']->v++;
p=p->child[*str-'a'];
str++;
}
}
int Find(char* str)
{
Tri* p=&root;
while(*str!=NULL)
{
if(p->child[*str-'a']==NULL)
return 0;
p=p->child[*str-'a'];
str++;
}
return p->v;
}
int main()
{
char a[100];
Init();
while(gets(a) && a[0]!='\0')
{
CreateDic(a);
}
while(gets(a))
{
cout<<Find(a)<<endl;
}
return 0;
}原文地址:http://blog.csdn.net/a809146548/article/details/45156903