题目
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.
The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.
Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.
Input
The first line contains one integer n (2≤n≤10^5) — the number of trophies.
The second line contains n characters, each of them is either G or S. If the i-th character is G, then the i-th trophy is a golden one, otherwise it’s a silver trophy.
Examples
input
10
GGGSGGGSGG
output
7
input
4
GGGG
output
4
intput
3
SSS
output
0
Note
In the first example Vova has to swap trophies with indices 4 and 10. Thus he will obtain the sequence “GGGGGGGSGS”, the length of the longest subsegment of golden trophies is 7.
In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is 4.
In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than 0.
题意:输入一个长度为n的字符串,字符串只包含字符G和S,有且仅有一次交换两个字符的机会,获得连续G的个数。
解题思路:首先分别计算S和G的个数,当S的个数小于2时,直接输出G的个数即可;否则,遍历字符串,当字符不为S时,对其长度L进行累加,取当前G和L的最大值;当字符为S时对其进行累加,并且当字符S的个数为大于1时,然后对其回溯到上次出现的位置,对字符S个数进行减1,且长度L–,继续遍历;最后输出连续G的个数和G的总个数的最小值。
AC–Code
import java.util.Scanner;
public class CF1082Bsove {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = sc.next();
sc.close();
int sCount = 0;
int gCount = 0;
for (int i = 0; i <str.length(); i++)
{
if(str.charAt(i)=='S')
{
sCount++;
}
else
{
gCount++;
}
}
if(sCount<2)
{
System.out.println(gCount);
return ;
}
int sFar = 0;
int l = 0;
int maxl = 0;
for(int i =0;i<n;i++)
{
if(str.charAt(i)=='S')
{
sFar++;
}
while(sFar>1)
{
if(str.charAt(i-l)=='S')
{
sFar--;
}
l--;
}
l++;
maxl = Math.max(maxl, l);
}
System.out.println(Math.min(maxl, gCount));
}
}