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

猜你喜欢

转载自blog.csdn.net/asbbv/article/details/112019534