HDOJ 1039 Easier Done Than Said?

本文探讨了在解决字符串匹配问题时,从复杂到简洁的算法优化过程,并提供了两种不同阶段的实现方式,旨在提高效率并减少错误。通过实例演示,展示了如何在保持代码清晰的同时,确保解决方案的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接


简单的题目,一开始用了太复杂(太笨)的做法做了。自己测了很多数据感觉没错不过却一直WA.


现在贴出来有空再看看吧:


#include <iostream>
#include <string>
using namespace std;
bool judge(char a)//判断是否是元音
{
	if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u')
		return true;
	return false;
}
int main()
{
	int count;//计算元音个数
	int vow,con,same;//记录连续的元音,辅音个数
	string t;
	while(cin>>t&&t!="end") 
	{
		bool flag = false; //判断是否为元音
		bool res = true; //记录结果
		count = 0;
		vow = con = 1 ;
		for(int i=0;i<t.size();i++)
		{
			if(judge(t[i]))
			{
				count++;
				for(int j=i+1;j<t.size()&&judge(t[j]);j++){
					if((t[j-1]==t[j])&&(t[j]!='e'&&t[j]!='o'))
					{
						res = false ;
						break;
					}
					vow ++ ;}
				if(vow > 3){
					res = false;
					break;
				}
			}
			else 
			{
				for(int j=i+1;j<t.size()&&!judge(t[j]);j++){
					if((t[j-1]==t[j])&&t[j]!='e'&&t[j]!='o')
					{
						res = false ;
						break;
					}
					con ++ ;}
				if(con > 3){
					res = false;
					break;
				}
			}
		}
		if(!count)
			res = false;
		if(res)
			cout<<"<"<<t<<"> is acceptable."<<endl;
		else
			cout<<"<"<<t<<"> is not acceptable."<<endl;
	}
	return 0;
}

					

 这是后来写的,简洁明了,一遍AC:


#include <iostream>
#include <string>
using namespace std;
bool judge(char a)//判断是否是元音
{
	if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u')
		return true;
	return false;
}
int main()
{
	int count;//计算元音个数
	string t;
	while(cin>>t&&t!="end") 
	{
		bool flag = false; //判断是否为元音
		bool res = true; //记录结果
		count = 0;
		for(int i=0;i<t.size();i++)
		{
			if(judge(t[i]))
				count++;
			if(i<t.size()-2)// 不能连续3个元音或者辅音
			{
				if(judge(t[i])&&judge(t[i+1])&&judge(t[i+2]))
					res = false;
				if(!judge(t[i])&&!judge(t[i+1])&&!judge(t[i+2]))
					res = false;
			}
			if(i<t.size()-1)//不能有重复的
			{
				if(t[i]==t[i+1]&&t[i]!='o'&&t[i]!='e')
					res = false;
			}
		}
		if(!count)  //至少一个元音
			res = false;
		if(res)
			cout<<"<"<<t<<"> is acceptable."<<endl;
		else
			cout<<"<"<<t<<"> is not acceptable."<<endl;
	}
	return 0;
}

					




 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值