51nod 1391:01串

题目来源:  Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 40  难度:4级算法题
 收藏
 关注
给定一个01串S,求出它的一个尽可能长的子串S[ i..j],满足存在一个位置i<=x <=j, S[i..x]中0比1多,而S[x + 1..j]中1比0多。求满足条件的最长子串长度。
Input
一行包含一个只由0和1构成的字符串S。 S的长度不超过1000000。
Output
一行包含一个整数,表示满足要求的最长子串的长度。
Input示例
10
Output示例
0

hash啊。记录出现值的第一位置,之后如果出现比这个值小于1的数,就说明这个位置到此处的位置中0比1多。

代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;

#define maxn 1000003

int val[maxn];
int hash_val[maxn];
int le[maxn];
int ri[maxn];

char test[maxn];

int main()
{
	//freopen("i.txt", "r", stdin);
	//freopen("o.txt", "w", stdout);

	int i, res, cur, len;

	scanf("%s", test);
	len = strlen(test);

	for (i = 0; i < len; i++)
	{
		if (test[i] == '0')
		{
			val[i] = -1;
		}
		else
		{
			val[i] = 1;
		}
	}

	memset(hash_val, -1, sizeof(hash_val));
	cur = 0;
	for (i = 0; i < len; i++)
	{
		cur = cur + val[i];
		if (cur < 0)
		{
			le[i] = i + 1;
		}
		else
		{
			if (hash_val[cur + 1] != -1)
			{
				le[i] = i - hash_val[cur + 1];
			}
			else
			{
				hash_val[cur] = i;
				le[i] = 0;
			}
		}
	}

	memset(hash_val, -1, sizeof(hash_val));
	cur = 0;
	for (i = len - 1; i >= 0; i--)
	{
		cur = cur + val[i];
		if (cur > 0)
		{
			ri[i] = len - i;
		}
		else
		{
			if (hash_val[-(cur - 1)] != -1)
			{
				ri[i] = hash_val[-(cur - 1)] - i;
			}
			else
			{
				hash_val[-(cur)] = i;
				ri[i] = 0;
			}
		}
	}
	res = 0;
	for (i = 0; i < len; i++)
	{
		if (le[i] > 0 && ri[i + 1] > 0)
			res = max(res, le[i] + ri[i + 1]);
	}
	printf("%d\n", res);
	//system("pause");
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值