1393 0和1相等串
- 1 秒
- 131,072 KB
- 20 分
- 3 级题
给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。
收起
输入
一个字符串,只包含01,长度不超过1000000。
输出
一行一个整数,最长的0与1的个数相等的子串的长度。
输入样例
1011
输出样例
2
题解:将'0'看成-1,'1'看成1,用sum一直累加,当第一次出现某个值的时候,用map记录其位置(意味着一个周期的开始),当再出现这个值的话,就意味着周期的终点。
下标: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
字符串: 0 1 0 1 1 1 1 1 0 1 0 1 0 1 0 1
sum: 0 -1 0 -1 0 1 2 3 4 3 4 3 4 3 4 3 4
#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=max(tree[rt<<1],tree[rt<<1|1])
#define nth(k,n) nth_element(a,a+k,a+n); // 将 第K大的放在k位
#define ko() for(int i=2;i<=n;i++) s=(s+k)%i // 约瑟夫
#define ok() v.erase(unique(v.begin(),v.end()),v.end()) // 排序,离散化
using namespace std;
inline int read(){
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
typedef long long ll;
const double pi = atan(1.)*4.;
const int M=1e3+5;
const int N=1e6+5;
char s[N];
map<int,int>mapp;
int main(){
scanf("%s",s+1);
int len=strlen(s+1);
len++;
int sum=0;
mapp[0]=0;
int ans=0;
for(int i=1;i<len;i++){
if(s[i]=='0')
sum--;
else sum++;
if(mapp.count(sum))
ans=max(ans,i-mapp[sum]);
else
mapp[sum]=i;
}
printf("%d\n",ans);
return 0;
}