注意new的时候要初始化。
动态new申请:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
int total;
struct node *next[26];
node()
{
total=0;
memset(next,0,sizeof(next));
}
}*R;
int length;
char str[15];
void insert(struct node *root,int pos)
{
int i;
if (pos==length)
return;
if (root->next[str[pos]-'a']==NULL)
{
for (i=pos;i<length;i++)
{
root->next[str[i]-'a']=new struct node;
root->next[str[i]-'a']->total++;
root=root->next[str[i]-'a'];
}
}
else
{
root->next[str[pos]-'a']->total++;
insert(root->next[str[pos]-'a'],pos+1);
}
}
int finds(struct node *root,int pos)
{
if (pos==length)
return root->total;
else if (root->next[str[pos]-'a']==NULL)
return 0;
return finds(root->next[str[pos]-'a'],pos+1);
}
int main()
{
R=new struct node;
while (1)
{
scanf("%s",str);
getchar();
length=(int)strlen(str);
insert(R,0);
if (cin.peek()=='\n')
break;
}
while (scanf("%s",str)!=EOF)
{
length=(int)strlen(str);
printf("%d\n",finds(R,0));
}
}
预创建数组:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
int total;
int next[26];
}R[500005];
int length;
char str[15];
int counter=1;
void insert()
{
int index=0;
int i;
for (i=0;i<length;i++)
{
if (R[index].next[str[i]-'a']==0)
R[index].next[str[i]-'a']=counter++;
R[R[index].next[str[i]-'a']].total++;
index=R[index].next[str[i]-'a'];
}
}
int find()
{
int index=0;
int i;
for (i=0;i<length;i++)
{
if (R[index].next[str[i]-'a']==0)
return 0;
index=R[index].next[str[i]-'a'];
}
return R[index].total;
}
int main()
{
while (1)
{
scanf("%s",str);
getchar();
length=(int)strlen(str);
insert();
if (cin.peek()=='\n')
break;
}
while (scanf("%s",str)!=EOF)
{
length=(int)strlen(str);
printf("%d\n",find());
}
}