UVALive - 6439

本文介绍了一种通过替换字符来构建最长回文串的方法。该算法比较字符串两端的子串,若相同则进行替换,并使用字符串操作实现,提高了算法效率。

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

题目大意就是用字符来代替一段字符串,使改变后的字符串为回文串,求最大长度。

 

只要查看字符串两边的子串是否相同,相同就把这两个相同的子串变成一个符号,用string会快很多,用hash也行

#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio> 
#include<cstring>

using namespace std;

string str1,str2,str3;

int main()
{
	int T,ans;
	cin>>T;
	for(int t=1;t<=T;t++)
	{
		ans=0;
		cin>>str1;
		str2="";//空串 
		str3="";//空串 
		int len=str1.length();
		for(int i=0;i<len/2;i++)
		{
			str2=str2+str1[i];
			str3=str1[len-i-1]+str3;//也可以写成str3+str1[len/2+i],不过要判断len的奇偶性 
			if(str2==str3)//相等就换成字符 
			{
				str2=str3="";//清空 
				ans+=2; 
			}
		}
		if(str2!=""&&len%2==0) ans++; 
		if(len%2) ans++;
		printf("Case #%d: %d\n",t,ans);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值