给你一个只有0和1的字符串,你现在有一个操作,可以把相邻的一对0和1消去,问最后能得到的最短长度

方法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");
}
View Code

方法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");
}
View Code

方法2完胜!

猜你喜欢

转载自www.cnblogs.com/garrettlu/p/10665371.html