基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
Input
一个字符串,只包含01,长度不超过1000000。
Output
一行一个整数,最长的0与1的个数相等的子串的长度。
Input示例
1011
Output示例
2
思路:求一段01串相等的子串,那么可以将 0用-1表示,那么01相等的子串的总和为0,因此可以用a[i]保存 0->i 的总和,则当a[i]=a[j]时说明i->j间是一段 01相等串,因此只要找出 最大的 i-j即可,而 对于 a[i]=t,只要保存 最左边和最右边的下标。因此只要一个数组保存 为 总和为t的最左边的下标。同时 当 t==0时,0->i也是一段01子串,应该保存此时的下标值。还应当注意 a[t],t不能小于0,因此可以 t加上字符串的长度作为数组下标。
Code:
#include<iostream>
using namespace std;
const int MAX_N=2000005;
const int Len=1000005;
string str;
int ans;
int a[MAX_N];
int main()
{
ios::sync_with_stdio(false);
cin>>str;
for(int i=1,t=0;i<=str.size();++i)
{
t=(str[i-1]=='1')?t+1:t-1;
if(!t) ans=i;
if(!a[t+Len]) a[t+Len]=i;
else ans=max(ans,i-a[t+Len]);
}
cout<<ans<<endl;
return 0;
}