宝石串 - 前缀和
【代码】
#include<bits/stdc++.h>
using namespace std;
const int N = 1010000;
char s[N];
int sum[N],l[N << 1] = {0},r[N << 1] = {0}, ans = 0;
int main() {
scanf("%s",s + 1);
int n =strlen(s + 1);
sum[0]=0;
for(int i = 1; i <= n; ++i)
sum[i] = sum[i - 1] + (s[i] == 'G'? 1 :-1);
for(int i = 1; i <= n; ++i) {
if(l[sum[i] + N] == 0 && sum[i])
l[sum[i] + N] =i;
if(r[sum[n - i + 1] + N] == 0)
r[sum[n - i + 1] + N] = n - i + 1;
}
for(int i = 0; i <= 2 * N; ++i)
if(r[i] - l[i] > ans)
ans = r[i] - l[i];
printf("%d\n", ans);
return 0;
}