CodeForces - 873B - Balanced Substring 【 前缀和+map】题解

1.题目

You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string s l s l + 1 s l + 2… s r, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.

You have to determine the length of the longest balanced substring of s.

Input
The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s.

The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

Output
If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

Examples
Input
8
11010111
Output
4
Input
3
111
Output
0
Note
In the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.
In the second example it’s impossible to find a non-empty balanced substring.

2.代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<map>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn];
map<int, int>mp;
int main()
{
	int n;
	string str;
	cin >> n>>str;
	for (int i = 1; i <=n; i++)//将字符串转换为int数组
	{
		a[i]=str[i-1]-'0';
		if (a[i] == 0)
		{
			a[i] = -1;
		}
	}
	int ans=0,sum=0;
	for (int i = 1; i <=n; i++)
	{
		sum += a[i];  //前缀和
		if (mp[sum])
		{
			ans = max(ans, i - mp[sum]);//如果之前存在过这个和,现在又出现了,说明这个区间1,0个数是相同的,相减为长度
		}
		else
		{	
			mp[sum] = i;//利用map不能重复插入的特性,所以如果存在一定是这个值第一次出现时的位置
		}
		if (sum == 0)//如果前缀和出现零说明从一开始就是1,0个数相同
		{
			ans = max(ans, i);
		}
	}	
	cout << ans << endl;
	return 0;
}

链接: map用法.
链接: link.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林小鹿@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值