字典树水题,求公共前缀的个数。。。
#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;
}

本文介绍了一个使用字典树(Trie)解决公共前缀问题的简单实现。通过插入字符串到字典树中,并查找字符串来统计公共前缀的数量。文章包含完整的C++代码示例,演示了字典树节点的定义、初始化、插入操作及查找过程。
178

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



