爆0求助

P1241 括号序列

peterJr @ 2024-07-22 11:46:17

在string长度增加的过程中,循环次数也变多,造成可能的死循环以及可能的(已经造成的)WA.求助QwQ

#include <iostream>
#include <string>
#include <algorithm>

#define DEBUG 0 //需要就打开,不需要不用管,监视变量用的

using namespace std;

string s;
int vis[107];

int main()
{
    cin >> s;

    for (int i = 0; i < s.size(); ++i)
    {
        if (s[i] == ')')
        {
            for (int j = i - 1; j >= 0; --j)
                if (s[j] == '(')
                {
                    vis[i] = 1;
                    vis[j] = 1;
                    break;
                }
        }
        if (s[i] == ']')
        {
            for (int j = i - 1; j >= 0; --j)
                if (s[j] == '[')
                {
                    vis[i] = 1;
                    vis[j] = 1;
                    break;
                }
        }
    }

    if (DEBUG)
    {
        cout << "Got string:";
        for (int i = 0; i < s.size(); ++i)
            cout << s[i] << " " << vis[i] << endl;
    }

    int n = s.size();

    for (int i = 0; i < s.size(); ++i)
        if (!vis[i])
        {
            if (s[i] == '(')
            {
                if (i != s.size() - 1) s.insert(s.begin() + i + 1, ')');
                else s.push_back(')');
                if (DEBUG) cout << s << endl;
            }
            if (s[i] == ')')
            {
                s.insert(s.begin() + i, '(');
                if (DEBUG) cout << s << endl;
            }
            if (s[i] == '[')
            {
                if (i != s.size() - 1) s.insert(s.begin() + i + 1, ']');
                else s.push_back(']');
                if (DEBUG) cout << s << endl;
            }
            if (s[i] == ']')
            {
                s.insert(s.begin() + i, '[');
                if (DEBUG) cout << s << endl;
            }
        }

    cout << s << endl;

    return 0;
}

|