题意:统计以某个字符串为前缀的单词的数量。
思路:字典树,建树的同时统计,节点字符的个数
#include<iostream>
#define max 26
using namespace std;
struct node
{
int count;//记录此节点字串的个数
node *next[max];//子节点
node()//构造函数 new node()时候自动执行
{
count=1;
for(int i=0;i<max;i++)
next[i]=NULL;
}
};
void insert(node *&root,char *word)
{
node *l=root;
int i=0,branch=0;
//if(l==NULL) { l=new node();root=l;}
while(word[i]!='\0')
{
branch=word[i]-'a';
if(l->next[branch]) {l->next[branch]->count++;}//下一个节点如果不是NULL 则下一个节点的count +1
else l->next[branch]=new node();//一个节点如果是NULL 则开辟新的节点
l=l->next[branch];//指针指向本身的NEXT 也就是下一个节点
i++;
}
}
int search(node *root,char *word)//与查找类似
{
node *l=root;
int i=0,branch=0,ans;
//if(l==NULL) return 0;
while(word[i]!='\0')
{
branch=word[i]-'a';
if(l->next[branch]){l=l->next[branch];ans=l->count;}
else return 0;
i++;
}
return ans;
}
int main()
{
char word[100],b[10];
//node *root=NULL;
node *root=new node();
while(gets(word))
{
if(word[0]=='\0') break;
insert(root,word);
}
while(gets(b))
printf("%d\n",search(root,b));
//system("pause");
return 0;
}