https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1393
当0和1的数量差值为0时,进行记录和ans进行比较,其他的,差值相等时,0和1的数量一定相等。用后面的减前面的情况。
#include<bits/stdc++.h> using namespace std; char s[1000005]; int a[1000005],b[1000005]; map<int,int>m; main() { int len,i,ans=0,t; scanf("%s",s); len=strlen(s); for(i=0;i<len;i++) { a[i+1]=a[i]; b[i+1]=b[i]; if(s[i]=='0') a[i+1]++; if(s[i]=='1') b[i+1]++; t=b[i+1]-a[i+1]; if(t==0) ans=max(ans,i+1); else { if(m[t]) ans=max(i+1-m[t],ans); else m[t]=i+1; } } printf("%d",ans); }