方法1:
#include <iostream> #include <string> using namespace std; void main() { int nLength = 0; string str0And1; cin >> nLength; cin >> str0And1; for (int i = 0; i < str0And1.size() - 1; i++) { if (str0And1[i] + str0And1[i + 1] == 0x61) { str0And1.erase(i, 2); if (str0And1.size() < 2) { break; } if (i > 1) { i -= 3; } else { i = -1; } } } cout << str0And1.size() << endl; system("pause"); }
方法2:
从一个含有0或1的字符串到只含有0或只含有1或为空的字符串,中间发生了0-1的相消,那么最终剩下的是0还是1,还是空呢,就要看0和1的个数啦!
先交一波智商税。。。
#include <iostream> #include <string> #include <algorithm> using namespace std; void main() { int nLength = 0; string str0And1; unsigned int num0 = 0; unsigned int num1 = 0; cin >> nLength; cin >> str0And1; for (unsigned int i = 0; i < str0And1.size(); i++) { if (str0And1[i] == 0x30) num0++; else num1++; } cout << nLength - min(num0,num1) * 2 << endl; system("pause"); }
方法2完胜!