You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals tor - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.
You have to determine the length of the longest balanced substring of s.
The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.
The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.
If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.
8 11010111
4
3 111
0
In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.
In the second example it's impossible to find a non-empty balanced substring.
这道题比赛的时候没写出来,没想到要用前缀和。给定的字符串可以把其中的0看成-1,这样的话更能够体现一一对应的特点。然后求整个的前缀和,前缀和相同的时候两个地址相减,求出最大值即可。可以用结构体来写,也可以用map。
#include<bits/stdc++.h>
using namespace std;
int a[100100];
map <int,int> m;
char s[100100];
int main()
{
int n;
scanf("%d %s",&n,s + 1);
for(int i = 1; i <= n; i++)
{
if(s[i] == '0') a[i] = -1;
else a[i] = 1;
}
int ans = 0
int sum = 0;
m[0] = 1;
for(int i = 1; i <= n; i++)
{
ans += a[i];
if(m[ans])
sum = max(sum,i - m[ans] + 1);
else m[ans] = i + 1;
}
printf("%d\n",sum);
return 0;
}