字典树水题,求公共前缀的个数。。。
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
using namespace std;
typedef struct Tire
{
int count;
struct Tire *next[26];
}*Node,T;
Node a;
void init()
{
a=(Node)malloc(sizeof(T));
for(int i=0;i<26;++i)
a->next[i]=NULL;
}
void insert(string s)
{
Node head=a;
int n=s.size();
for(int i=0;i<n;++i)
{
int k=(int)(s[i]-97);
if(head->next[k]==NULL)
{
head->next[k]=new T;
head=head->next[k];
head->count=1;
for(int i=0;i<26;++i)
head->next[i]=NULL;
}
else {
head=head->next[k];
head->count++;
}
}
}
int find(string s)
{
int n=s.size();
Node head=a;
for(int i=0;i<n;++i)
{
int k=(int)(s[i]-97);
if(head->next[k]) head=head->next[k];
else return 0;
}
return head->count;
}
int main()
{
char ch[10];
init();
while(gets(ch),strcmp(ch,""))
insert(ch);
while(gets(ch))
cout<<find(ch)<<endl;
return 0;
}