思路:
这道题可以抽象成:给定一个由 a a a 或 b b b 组成的序列,如果连续的 a a a 或 b b b 的数量大于等于 2 2 2,输出”YES“;否则输出”NO“。
下面就是如何求连续的
a
a
a 或
b
b
b 的数量。我们可以用 while 循环来解决: while(s[i] == s[i + 1]) 计数器++
核心代码:
string s;
cin >> s;
int f = 1;
int i = 0;
int n = s.size();
int ans = 0;
while (i < n) {
int j = i;
while (s[j] == s[j + 1])
j++;
if ((j - i + 1) < 2) { //如果连续相同的数目小于则2不能
cout << "NO" << endl;
f = 0;
break;
}
i = j + 1;
}
if (f) {
cout << "YES" << endl;
}
完整代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
typedef long long ll;
int t;
string s;
int main() {
ios::sync_with_stdio(false);
cin >> t;
while (t--) {
cin >> s;
int f = 1;
int i = 0;
int n = s.size();
int ans = 0;
while (i < n) {
int j = i;
while (s[j] == s[j + 1])
j++;
if ((j - i + 1) < 2) { //如果连续相同的数目小于则2不能
cout << "NO" << endl;
f = 0;
break;
}
i = j + 1;
}
if (f) {
cout << "YES" << endl;
}
}
return 0;
}