给定一个仅包含0或1的字符串,现在可以对其进行一种操作:
当有两个相邻的字符其中有一个是0另外一个是1的时候,可以消除掉这两个字符。
这样的操作可以一直进行下去直到找不到相邻的0和1为止。
问这个字符串经历了操作以后的最短长度。
输入格式
第一行包含一个整数 n,表示字符串的初始长度。
第二行为所给字符串。
输出格式
输出共一行,包含一个整数,表示问题的解。
数据范围
1≤n≤2∗1051≤n≤2∗105
输入样例1:
4
1100
输出样例1:
0
输入样例2:
5
01010
输出样例2:
1
假设有n个1,m个0,两两相消,那么最后剩下的字符串的最小值一定是abs(n-m),那么这个最小值是否能取到,经尝试后发现这个最小值一定能取到。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
string str;
cin >> n;
cin >> str;
int zeros = 0, ones = 0;
for (auto s : str) {
if (s == '1')
ones++;
else
zeros++;
}
cout << abs(ones - zeros) << endl;
}
方法二,使用栈进行操作
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
int main()
{
int n;
string str;
cin >> n;
cin >> str;
stack<char> st;
for (auto s : str) {
if (st.empty()) {
st.push(s);
}
else if (st.top() == '1' && s == '0')
st.pop();
else if (st.top() == '0' && s == '1')
st.pop();
else
st.push(s);
}
cout << st.size() << endl;
}