题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
经典的字典树题目。。
字典树:又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。
AC code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int count;
struct node *next[26];
};
struct node *root;
void insert(char *s)/*建立字典树*/
{
int i,j,len;
struct node *current,*newset;/*current相当于移动的指针,newset代表新建节点*/
len=strlen(s);
if(len==0) return ;
current=root;
for(i=0;i<len;i++)
{
if(current->next[s[i]-'a']!=NULL)/*如果前缀以前出现过*/
{
current=current->next[s[i]-'a'];
current->count=current->count+1;/*count代表当前字符或字符串出现的次数*/
}
else
{
struct node *newset=(struct node *)malloc(sizeof(struct node));/*如果前缀没有出现过,则需要新建节点*/
for(j=0;j<26;j++)
{
newset->next[j]=NULL;
}
current->next[s[i]-'a']=newset;
current=newset;
current->count=1;
}
}
}
int find(char *s)/*定义查找字符串*/
{
int i,len;
struct node *current;
len=strlen(s);
if(len==0) return 0;
current=root;
for(i=0;i<len;i++)
{
if(current->next[s[i]-'a']!=NULL)
{
current=current->next[s[i]-'a'];
}
else
{
return 0;
}
}
return current->count;
}
int main()
{
char str[101];
int i,ans;
root=(struct node *)malloc(sizeof(struct node));
for(i=0;i<26;i++)
{
root->next[i]=NULL;
}
while(gets(str)&&str[0]!='\0')
{
insert(str);
}
while(~scanf("%s",str))
{
ans=find(str);
printf("%d\n",ans);
}
return 0;
}
又写了一段差不多的,不过看起来跟美观了~~~哈哈
AC code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int count;
struct node *next[26];
};
struct node *root;
struct node *newset()/*实现建立节点功能*/
{
struct node *current;
current=(struct node *)malloc(sizeof(struct node));
for(int i=0;i<26;i++)
{
current->next[i]=NULL;
}
current->count=1;
return current;
}
void insert(char *s)/*实现建立字典树功能*/
{
struct node *current;
int len=strlen(s);
if(len==0) return ;
current=root;
for(int i=0;i<len;i++)
{
if(current->next[s[i]-'a']!=NULL)
{
current=current->next[s[i]-'a'];
current->count=current->count+1;
}
else
{
current->next[s[i]-'a']=newset();
current=current->next[s[i]-'a'];
}
}
}
int find(char *s)/*实现查找功能*/
{
struct node *current;
int len=strlen(s);
if(len==0) return 0;
current=root;
for(int i=0;i<len;i++)
{
if(current->next[s[i]-'a']!=NULL)
{
current=current->next[s[i]-'a'];
}
else
{
return 0;
}
}
return current->count;
}
int main()
{
char str[101];
int i,ans;
root=newset();
while(gets(str)&&str[0]!='\0')
{
insert(str);
}
while(~scanf("%s",str))
{
ans=find(str);
printf("%d\n",ans);
}
return 0;
}