memory limit per test256 megabytes
inputstandard input
outputstandard output
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 00 or replace all occurrences of this character with 11.
Is it possible to perform some number of moves so that the resulting string is an alternating binary string††?
For example, consider the string abacabaabacaba. You can perform the following moves:
Replace aa with 00. Now the string is 0b0c0b00b0c0b0.
Replace bb with 11. Now the string is 010c010010c010.
Replace cc with 11. Now the string is 01010100101010. This is an alternating binary string.
††An alternating binary string is a string of 00s and 11s such that no two adjacent bits are equal. For example, 0101010101010101, 101101, 11 are alternating binary strings, but 01100110, 0a0a00a0a0, 1010010100 are not.
Input
The input consists of multiple test cases. The first line contains an integer t� (1≤t≤1001≤�≤100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains an integer n� (1≤n≤20001≤�≤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�.
Output
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).
Example
input
8
7
abacaba
2
aa
1
y
4
bkpt
6
ninfia
6
banana
10
codeforces
8
testcase
output
YES
NO
YES
YES
NO
YES
NO
NO
Note
The first test case is explained in the statement.
In the second test case, the only possible binary strings you can make are 0000 and 1111, neither of which are alternating.
In the third test case, you can make 11, which is an alternating binary string.
思路
这道题可以就是采用一个大一点的模拟进行遍历,开一个str数组 记录这个字符是
变0还是 变成1,接着把该字符全部在str数组里描述为0或1,相邻的不能相同,即可。
代码如下
#include<stdio.h>
#include<string.h>
int main()
{
int k;
scanf("%d", &k);
while (k--)
{
int n;
scanf("%d", &n);
char arr[2222] = { 0 };
scanf("%s",arr);
int str[2222];
for (int i = 0; i < n; i++)//这不能初始化为0
{
str[i] = 2;
}
int len = strlen(arr);
int flag = 1;
str[0]= 0;//第一个字符定义为0或者1都可以
for (int i = 1; i < len; i++)
{
if (arr[i] == arr[0])//把他们都变成一样的0或1
{
str[i] = 0;
}
}
for (int i = 1; i < len; i++)
{
if (str[i] == str[i-1])
{
flag = 0;
printf("NO\n");
break;
}
if (str[i-1] != str[i] && str[i-1] == 0)
{
if (str[i]!=2) continue;
str[i] = 1;
for (int j = i + 1; j < len; j++)
{
if (arr[j] == arr[i])
{
str[j] = 1;
}
}
}
else if (str[i] != str[i-1] && str[i-1] == 1)
{
if (str[i]!=2) continue;
str[i] = 0;
for (int j = i + 1; j < len; j++)
{
if (arr[j] == arr[i])
{
str[j] = 0;
}
}
}
}
if (flag) printf("YES\n");
}
}
//i_kmling-=-