input
7
babba
abaac
codeforces
zeroorez
abcdcba
bbbbbbb
a
output
1
1
0
1
1
4
0
题目大意:给你一个字符串,可以更换任意位置的字符更换为任意字符,要求字符串中间不能存在长度在1以上的回文子串,求最少修改次数。
思路:
拿到这个题我们想大致模拟一下,我们确保子串中不能有回文子串,那么更长的回文子串,肯定由短的回文子串共享,比如abcba由bcb贡献。因此若我们破坏bcb,那么这个字符串就被破坏。我们发现,最短的回文子串,要么属于长度为2的aa型,要么就是长度为3的aba型和aaa型。也就是确保字符串中不能存在长度为2或3的回文子串。根据贪心思维我们要找到最优的破坏解。对于aa型,我们选择破坏第二个a最优,因为第二个a很可能对后面的子串有贡献;对于aba型,选择破坏最后一个最优,避免对后面的贡献;对于aaa型,需要替换两个字符才能不是回文串,能破坏第二三个最优。
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N = 2e5+5;
int main()
{
int t;
cin >> t;
while(t--)
{
int res = 0;
string str;cin >> str;
for(int i = 0; i < str.size() - 1; i ++)
{
if(str[i] == '#') continue;
if(str[i] == str[i + 1])
str[i+1] = '#',res++;
if(str[i] == str[i + 2] && i + 2 < str.size())
str[i+2] = '#',res++;
}
cout << res << endl;
}
}