一按要求模拟的水题
字符消除游戏,规则如下:
1)字符串仅由A、B、C三种字母组成;
2)如果串中有连续的相同字符,就可以进行消除操作。消除完后新的字符串可能又出现连续相同字符,那么可以再次消除,以此类推,直到不能进行消除操作。
现在你有一个给定字符串str,为了消除最多的字母,你可以在str中的任何位置插入一个字母AorBorC(只能插入一次),然后进行消除操作,问最多可以消除多少个字母。
Input
输入第一行是一个整数T(1<=T<=100),代表测试数据的数量。
之后T行每行一个由'A''B''C'组成的字符串s,长度不超过100
Output
对于每一行输入的字符串,输出小Hi最高能得到的分数。
Sample Input
3
ABCBCCCAA
AAA
ABC
Sample Output
9
4
2
【思路】
由于数据范围较小,直接模拟插入并计算可消除的数量即可。
AC代码如下:
#include <bits/stdc++.h>
using namespace std;
int del(string s)
{
int nums = 0;
bool cont = true;
while(cont){
cont = false;
string tmp = "";
int len = s.length();
for(int i = 0; i < len-1; ){
if(s[i] == s[i+1]) {
cont = true;
char cur = s[i];
for(; s[i] == cur && i < len; i++){
nums++;
s[i] = '*';
}
}
else i++;
}
for(int i = 0; i < len; i++){
if(s[i] != '*')
tmp += s[i];
}
s = tmp;
}
return nums;
}
int main()
{
int t;
string str, to_solve;
cin >> t;
while(t--){
cin >> str;
int ans = 0;
int len = str.length();
for(int i = 0; i <= len; i++){
for(char ch = 'A'; ch <= 'C'; ch++){
to_solve = str.substr(0, i) + ch + str.substr(i, len);
ans = max(ans, del(to_solve));
}
//cout << to_solve << endl;
}
cout << ans << endl;
}
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。