hdu 1075(What Are You Talking About)

题目链接:

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;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值