51nod 1393 0和1相等串(鸽巢原理)

1393 0和1相等串

基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题

给定一个0-1串,请找到一个尽可能长的子串,其中包含的0与1的个数相等。

Input

一个字符串,只包含01,长度不超过1000000。

Output

一行一个整数,最长的0与1的个数相等的子串的长度。

Input示例

1011

Output示例

2


思路:当0和1的差值与上一个0和1的差值相同时,那么他们之间的字符串中0和1的数目是相同的。求出最大的就行了。

举个例子:前面0,1为a, b,后面0,1为aa, bb, a - b = aa - bb,  得 a - aa = b - bb;


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <functional>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
#define esp  1e-8
const double PI = acos(-1.0);
const double e = 2.718281828459;
const int inf = 2147483647;
const long long mod = 1000000007;
//freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
//freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中cin
char s[1000005];
int num[2000005];
int sum[2];
int main()
{

    while (~scanf("%s", s))
    {
        memset(num, 9999, sizeof(num));
        int x = num[0];
        memset(sum, 0, sizeof(sum));
        int ans = 0;
        num[1000000] = 0;
        for (int i = 0; s[i]; ++i)
        {
            if (s[i] == '0')
                sum[0]++;
            else
                sum[1]++;
            if (num[sum[0] - sum[1] + 1000000] == x)
            {
                num[sum[0] - sum[1] + 1000000] = i;
            }
            else
            {
                ans = max(ans, i - num[sum[0] - sum[1] + 1000000]);
            }
            if (sum[0] == sum[1])              //如果发现相等直接取最大
                ans = max(ans, i + 1);
        }
        printf("%d\n", ans);
    }
    
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值