传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1251
想象一下一个汉字后面可能接的数目,即使以10个数字作为基准,那花费的空间也是不敢想象的。
代码如下:
#include<iostream>
#include<cstring>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int maxn=1000;
char str[100];
struct Node
{
int count;//当前出现的次数
struct Node* next[26];//共有26个英文字母
};
Node* root;
void insert(char* s)
{
int i;
int len=strlen(s);
Node *current,*newset;
if(len==0) return;
current=root;
for(i=0;i<len;i++)
{
if(current->next[s[i]-'a']!=NULL)
{
//current->count=current->count+1;
current=current->next[s[i]-'a'];
current->count=current->count+1; //有root的存在所以顺序才发生变化,因为current先从root变化到第一个字母,之后才是计数的变化
}
else
{
newset=(Node*)malloc(sizeof(Node));
current->next[s[i]-'a']=newset; //这一行写的时候有点犹豫,,
for(int j=0;j<26;j++)
newset->next[j]=NULL;
current=newset;
current->count=1;
}
}
}
int find(char*s)
{
int i;
int len=strlen(s);
if(len==0) return 0;
struct Node*current;
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(void)
{
int n,m;
int i,j,k;
root=(Node*)malloc(sizeof(Node)); //根节点初始化
for(i=0;i<26;i++)
root->next[i]=NULL; //忘了这一个,一直溢出
while(gets(str)&&str[0]!='\0')
insert(str);
while(gets(str))
cout<<find(str)<<endl;
}