Case of the Zeros and Ones

Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.
Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

Input
First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has.
The second line contains the string of length n consisting only from zeros and ones.

Output
Output the minimum length of the string that may remain after applying the described operations several times.
Examples
Input

4
1100

Output

0

Input

5
01010

Output

1

Input

8
11101111

Output

6

Note
In the first sample test it is possible to change the string like the following:1100->10->(empty) .
In the second sample test it is possible to change the string like the following: 01010->010->0.
In the third sample test it is possible to change the string like the following: 11101111->111111.

题意:给你一个字符串,如果字符串中相邻的两个字符分别为0和1,那么就将这两个字符串移出该字符串,求最后这个字符串的最小长度。
题目分析:
求的是字符串的最小长度,所以我们应该将字符串中的相邻的0,1全部移除。可以用栈来进行操作:
如果栈为空,那么直接将下一个字符放入栈中,我们假设放入的字符为1
那么如果下一个字符为0,则将栈中元素移除一个
如果下一个字符还是1,则将这个1再放入栈中
最后栈中的元素个数便是字符串的最小长度。
上代码!

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
const int N=2e5+5;
int a[N];       //用数组模拟栈
char s[N];
int main()
{
    int n,top=0; //top为栈顶
    cin>>n;
    cin>>s;
    for(int i=0;i<n;i++)
    {
        if(top==0) a[++top]=s[i];  //如果栈中没有元素,就将s[i]直接放入
        else if(a[top]==s[i]) a[++top]=s[i];//与栈中元素相同,放入栈
        else a[top--]=0;           //与栈中元素不同,栈弹出一位
    }
    cout<<top<<endl;               //输出栈中元素
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lwz_159

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

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

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

打赏作者

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

抵扣说明:

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

余额充值