C. Canine poetry (贪心、思维)

题目

思路:
首先可以知道如果我们要消灭长度>=4的回文串,那么这个大的回文串必然包含小的回文串。所以我们其实只要消灭小的回文串就可以了。其实就是干掉aaa、aba、aa这三种。那么对于很长的一串回文串我们要使其任何子串都无长度>=2的回文串,我们从头开始遍历。如果开始出现aa,贪心一下我们干掉第二个字符,这样会尽可能减少a与之后的形成回文串。类似,aaa干掉后两个,aba干掉第三个,细节见代码。

Code:

#include<iostream>
#include<string>
using namespace std;
int main()
{
   
	int t;cin >> t;
	while (t--)
	{
   
		string str;cin >> str;
		int n = str.size();
		int ans = 0;
		for (int i = 0;i < n;i++)
		{
   
			if (str[i] == '#')continue;
			if ( i + 2 <= n - 1&&str[i] == str[i + 2] )
			{
   
				ans++;
				str[i+2] = '#';
			}
			if ( i + 1 <= n - 1&&str[i] == str[i + 1])
			{
   
				ans++;
				str[i + 1] = '#';
			}
		}
		cout << ans << endl;
	}
}
全部评论

相关推荐

10-17 23:18
已编辑
西北农林科技大学 Web前端
独行m:给25可以试试,但他只能给12,那就是纯纯的事精
秋招,不懂就问
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务