hdu1075Phone List(字典树)

1.题目链接:

   http://acm.hdu.edu.cn/showproblem.php?pid=1075

 

2.题意:根据所提供的“字典”,解破火星文。

 

3.参考代码一:

 

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char s1[3000],s2[3000];

struct node{
	char s[14];
	node* next[26];
	bool flag;   ///标记是否在字典树里
	node(){
		memset(s,0,sizeof(s));
		memset(next,0,sizeof(next));
		flag=0;
	}
};

node* root=NULL;

void build(node* t,int id){   ///建立
	
	if(!t->next[s2[id]-'a'])
		t->next[s2[id]-'a']=new node;
	
	if(s2[id+1])
		build(t->next[s2[id]-'a'],id+1);
	else   ///若找到则替换
	{
		strcpy(t->next[s2[id]-'a']->s,s1);
		t->next[s2[id]-'a']->flag=1;
	}
} 

int find(node* t,int id){   ///查找
	
	if(!t->next[s2[id]-'a'])
		return 0;
	
	if(s2[id+1]=='\0')
	{
		if(t->next[s2[id]-'a']->flag)	
		{
			printf("%s",t->next[s2[id]-'a']);
			return 1;
		}
		return 0;
	}
	
	return find(t->next[s2[id]-'a'],id+1);
}

int main()
{
	root=new node;
	
	int i,j;
	
	scanf("START%*c");
	
	while(scanf("%s%*c",s1) && strcmp(s1,"END"))
	{
		scanf("%s%*c",s2);
		build(root,0);
	}
	
	scanf("START%*c");
	
	while(gets(s1) && strcmp(s1,"END"))   ///句子记得用gets()接收
	{
		for(i=0;s1[i];i++)
		{
			if(!islower(s1[i]))   ///若不是小写字母
				putchar(s1[i]);   ///则直接输出
			else
			{
				j=0;
				while(islower(s1[i]))
					s2[j++]=s1[i++];
				s2[j]='\0';   ///别忘了赋'\0'
				i--;   ///防止读取非法内存(eg.假如说s1的长度是10,s[0]~s[9]存的是字符,s[10]是'\0',如果不i--下一层循环就会出错,所以要可特别注意!!!)
				if(!find(root,0))   ///找不到则原样输出
					printf("%s",s2);
				j=0;
			}
		}
		printf("\n");
	}
	
	return 0;
}


 

 

参考代码二:

 

 

#include <iostream>
#include <string>
#include <map>
using namespace std;

map<string,string>M;

int main()
{
	string a,b;

	cin>>a;

	while(cin>>a && a!="END")
	{
		cin>>b;
		M[b]=a;
	}

	cin>>a;

	getchar();

	char tmp[5000];

	while(1)
	{
		gets(tmp);

		if(!strcmp(tmp,"END"))
			break;

		int i,len=strlen(tmp);

		b="";

		for(i=0;i<len;i++)
		{
			if(!(tmp[i]>='a' && tmp[i]<='z'))
			{
				if(M[b]!="")
					cout<<M[b];
				else
					cout<<b;

				b="";

				cout<<tmp[i];
			}
			else
				b+=tmp[i];
		}

		cout<<endl;
	}

	return 0;
}


 




 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值