题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1075
Trie树的入门题。
推荐入门博客 : https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
题目跟1251那个入门差不多,只不过是多了一个替换,那就把单词最后储存替换的单词就行了。
#include<iostream>
#include<string>
using namespace std;
struct node{
int Count;//统计单词前缀出现次数
node *next[26];//叶子指针
int flag;//标记是否构成单词
string s;
node():Count(0),flag(0){//初始化
for(int i = 0;i < 26;i++)
next[i] = NULL;
}
};
void insert(node *root,string &s,string &s1)
{
node *temp = root;
int len = s.length();
for(int i = 0;i < len;i++)
{
int id = s[i] - 'a';
if(temp->next[id] == NULL)
temp->next[id] = new node();
temp = temp->next[id];
temp->Count = temp->Count + 1;//标记前缀数量
}
temp->flag = 1;//单词结束 完整单词
temp->s = s1;//记录下需要的单词
}
string find(node *root,string &s)
{
node *temp = root;
int len = s.length();
for(int i = 0;i < len;i++)
{
int id = s[i] - 'a';
if(temp->next[id] != NULL)
temp = temp->next[id];
else
return "";
}
if(temp->flag)
return temp->s;
else
return "";
}
int main()
{
node *root = new node();
string s,s1;
cin>>s;
while(cin>>s)
{
if(s=="END")
break;
cin>>s1;
insert(root,s1,s);
}
getchar();
while(getline(cin,s))
{
if(s=="START")
continue;
if(s=="END")
break;
string s1;
s1="";
int len=s.length();
for(int i=0;i<len;i++)
{
if(s[i] >= 'a' && s[i] <= 'z')
s1 += s[i];
else
{
string temp=find(root,s1);
if(!temp.empty())
cout<<temp;
else
cout<<s1;
cout<<s[i];
s1="";
}
}
cout<<endl;
}
return 0;
}