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 to r - 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.
后来看网上才发现如此巧妙的把n^2时间优化成n,用一个map,利用map不能重复插入的原则,第一个插入的一定是第一次出现的,那么一次遍历,如果在遇到这个值,直接求长度就可以了,妙啊
最后注意前缀和为0的情况,看代码注释
code:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
using namespace std;
int n;
string s;
int a[101000];
map<int,int>k;//优化时间的关键
int main(){
int i,j;
cin >> n >> s;//输入字符串
for(i = 0; s[i]; i++){
if(s[i]=='1')a[i+1] = 1;
else a[i+1] = -1;//将字符串转化成int数组
}
int sum = 0;
int ans = 0;
for(i = 1; i <= n; i++){
sum += a[i];
if(k[sum]){
ans = max(ans,i-k[sum]);//如果之前存在过这个和,现在又出现了,说明这个区间1,0个数是相同的,相减为长度
}
else k[sum] = i;//利用map不能重复插入的特性,所以如果存在一定是这个值第一次出现时的位置,所以这样后面再出现就相减求区间长度On复杂度求出
if(sum==0){
ans = max(ans,i);//如果前缀和出现零一定说明从一开始就是1,0个数相同,否则前缀和一定不可能为零
}
}
cout << ans << endl;
return 0;
}