题解:CF2225B Alternating String

· · 题解

题目分析

定义交替字符串 t 为:对于 t 中任意两个相邻的字符,他们都不相等。

给你一个由 ab 组成的字符串,判断能否通过最多 1 次操作后将这个字符串变成一个交替字符串。

思路

要想在最多 1 次操作之后使这个由 ab 组成的字符串变成交替字符串,则该字符串中相等连续字符最多有 2 个。因为,如果有 3 个相等连续字符,例如 aabbaa,则无法使它仅通过一次操作变成交替字符串。

定义 cnt 为该字符串中相等连续字符的个数。若 cnt\le 2,则输出 YES;否则,输出 NO

代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    int t;
    cin>>t;
    for(int tes=1;tes<=t;tes++){
        string s;
        cin>>s;
        int cnt=0,siz=s.size();
        for(int i=1;i<siz;i++){
            if(s[i]==s[i-1]) cnt++;
        }
        if(cnt<=2) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
    }
    return 0;
}