题意:
给一些单词,换行键后,查找以后输入的单词作为前缀的话们在之前出现过几次。
思路:
字典树模板----像查字典的顺序一样
#include<string>
#include<stdio.h>
#include<iostream>
using namespace std;
struct tire_node
{
int count;//前缀出现的次数
tire_node* next[27];//指针数组,装指针
bool exit;//是否构成单词
tire_node():count(0),exit(false){//清空,置NULL
for(int i=0;i<=26;i++)
next[i]=NULL;
}
};
void tire_insert(tire_node* root,string &word)//传入字典树根节点 ,单词
{
tire_node* node=root;//定义结构体指针
int len=word.size(),id,i=0;
while(i<len)//遍历单词
{
id=word[i]-'a';
if(node->next[id]==NULL)//如果子节点上没有出现过该字母
node->next[id]=new tire_node();//指向新的结构体指针
node=node->next[id];//将下一个子节点作为父亲节点
i++;//下一个字母
node->count+=1;//统计以这段字符串为前缀的单词
}
node->exit=true;//标记单词
}
int tire_search(tire_node *root,string &word)
{
tire_node* node=root;
int id,len=word.size(),i=0;
while(i<len)
{
id=word[i]-'a';
if(node->next[id]!=NULL)
node=node->next[id];
else
return 0;//该单词没有出现
i++;
}
return node->count;
}
int main()
{
int flag=0;
tire_node* root=new tire_node();
string s;
while(getline(cin , s))//输入字符串
{
if(s.empty())
{
flag=1;
continue;
}
if(!flag)
tire_insert(root,s);
else
// printf("%d\n",tire_search(root,s));运行不成功
cout<<tire_search(root,s)<<endl;
}
return 0;
}