题目链接:http://codeforces.com/contest/1082/problem/B
题意是输入长度为n的字符串,字符串只包含'S','G',问最多只能交换一次其中的任意两个字符,求出最长的'G'子串长度。
思路是首先我们先求出共有多少个'G',然后我们遍历字符串去寻找'S',找到后去计算'S'两边的'G'的长度,如果一个'S'两边的'G'的长度是小于Gcnt的,就说明当前的'G'的长度以外还存在'G',可以把其中的'S'替换掉,所以sum++,最后再特判一下只有一个'S'和没有'S'的情况就好了,方法不止这一种,看代码会更好理解一点。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int n;
string str;
int main()
{
scanf("%d",&n);
cin>>str;
int cnt = 0, Gcnt = 0, Scnt = 0, sum;
for(int i=0;i<n;i++){
if(str[i] == 'G') Gcnt ++;
}
for(int i=0;i<n;i++){
if(str[i] == 'S'){
Scnt ++;
sum = 0;
int l = i - 1, r = i + 1;
for(int j=i-1;j>=0;j--){
if(str[j] == 'G') sum ++;
else break;
}
for(int j=i+1;j<n;j++){
if(str[j] == 'G') sum ++;
else break;
}
if(Gcnt > sum) sum ++; // 判断能否把S替换成G
cnt = max(cnt, sum);
}
}
if(Scnt == 0) cnt = n;
if(Scnt == 1) cnt = n - 1;
printf("%d\n", cnt);
return 0;
}