题目链接: http://codeforces.com/problemset/problem/873/B
思路
看到这题应该就会有一个前缀和的想法,那么我们把1看成1,0看成-1,那么我们求前缀和,如果 sum[i] == sum[j] (i < j), 那么说明 i到j之间0和1的个数是相同的!
代码
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
typedef long long ll;
int main()
{
ios::sync_with_stdio(false);
int n;
while(cin >> n) {
string s;
cin >> s;
unordered_map<int, int> mp;
int sum = 0, maxn = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '1') sum += 1;
else sum += -1;
if(mp.count(sum)) {
maxn = max(maxn, i - mp[sum]);
} else {
mp[sum] = i;
}
// sum == 0
if(sum == 0) {
maxn = max(maxn, i + 1);
}
}
cout << maxn << endl;
}
return 0;
}