You are given a string
�
s consisting of lowercase Latin characters. In an operation, you can take a character and replace all occurrences of this character with
0
0 or replace all occurrences of this character with
1
1.
Is it possible to perform some number of moves so that the resulting string is an alternating binary string
†
†
?
For example, consider the string
abacaba
abacaba. You can perform the following moves:
Replace
a
a with
0
0. Now the string is
0b
0c
0b
0
0b0c0b0.
Replace
b
b with
1
The first line of each test case contains an integer
�
n (
1
≤
�
≤
2000
1≤n≤2000) — the length of the string
�
s.
The second line of each test case contains a string consisting of
�
n lowercase Latin characters — the string
�
s.
For each test case, output "YES" (without quotes) if you can make the string into an alternating binary string, and "NO" (without quotes) otherwise.
You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).
Inputcopy Outputcopy
8
7
abacaba
2
aa
1
y
4
bkpt
6
ninfia
6
banana
10
codeforces
8
testcase
YES
NO
YES
YES
NO
YES
NO
NO
用C语言写出符合题意的程序 并用中文解答
题目描述:
给定一个字符串,每次可以选择一个字符,将该字符的所有出现位置替换成0或1。问是否可以通过一些操作,将字符串变成一个交替的01串。
思路:
首先,如果字符串中相邻的两个字符相同,那么无论怎样替换都无法变成交替的01串,直接输出NO。
否则,我们可以贪心地考虑将所有的奇数位置替换成0,偶数位置替换成1。如果某个字符的所有出现位置都被替换成了同一个数字,那么我们就将其替换成另一个数字。例如,如果将所有a替换成0,那么所有出现的b都应该替换成1。这样做的目的是让每个字符的出现位置所对应的数字交替出现。
最后,我们只需要判断得到的字符串是否是交替的01串即可。
代码实现:
抱歉,这是C++的代码实现:
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 2005;
int t, n;
char s[MAXN];
int main() {
cin >> t;
while (t--) {
cin >> n >> s;
bool flag = true;
for (int i = 1; i < n; i++) {
if (s[i] == s[i-1]) { // 相邻字符相同
flag = false;
break;
}
}
if (!flag) { // 无法变成交替的01串