Title Description
There is a gem strings strung together by the ruby and emerald, only when the same number of ruby and emerald, when only the most stable gem string, prone to breaking. Ann wondered gemstone from a given string, the longest possible interception of a stable gem string, the number of jewels composition. Please help him.
Emerald with 'G' represent, ruby is represented by 'R'.
Input Format
His string consisting of G and R
Output Format
The longest string of gems stable number of jewels consisting of
Sample input and output
Input # 1 copy
GRGGRG
Output # 1 copy
4
Description / Tips
RGGR to answer.
Jewelry number <= 1000000
Ideas:
Green referred to as +1, -1 referred to as red, then the prefix and the calculation is, a subject to meet the requirements of section and zero, i.e., the prefix of the two end points of the interval and the difference is equal to zero (a value equal to the endpoint)
Thus for each value of a prefix and treated as follows:
When it first appears, it is recorded, or calculate the interval size and value of its appearance for the first time, and try to update the maximum interval
#include<iostream>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;
int main() {
char str[1000002];
int sum=0,ans=0;
map<int,int> m;m[0]=0; //前缀和的初始为0
cin>>(str+1); //字符串从1开始写入
for(int i=1; i<=strlen(str+1); i++) {
if(str[i]=='G')sum+=1;
else sum-=1;
if(m.find(sum)==m.end())m[sum]=i; //若sum的值为首次出现,则记录该值
else ans=max(ans,i-m[sum]); //尝试更新最大区间
}cout<<ans<<endl;
return 0;
}