68求调#8#9#10#11WA
查看原帖
68求调#8#9#10#11WA
1506652
guangyiliushan楼主2025/1/28 16:02
#include <bits/stdc++.h>
using namespace std;

void appendRes(string s, string &res, int start, int end)
{
    queue<char> jud;
    map<char, char> dic = {{'(', ')'}, {'[', ']'}, {']', '['}, {')', '('}};
    for (size_t i = start; i < end; ++i)
    {
        if (s[i] == '[' || s[i] == '(')
        {
            jud.push(s[i]);
            if (i + 1 < s.length() && s[i + 1] == dic.at(s[i]))
            {
                jud.push(s[++i]);
            }
            else
            {
                jud.push(dic.at(s[i]));
            }
        }
        else
        {
            jud.push(dic.at(s[i]));
            jud.push(s[i]);
        }
    }

    while (!jud.empty())
    {
        res += jud.front();
        jud.pop();
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    stack<char> matching = {};
    string s, res;
    cin >> s;
    int start = 0, count = 0;

    for (int i = 0; i < s.size(); ++i)
    {
        if (s[i] == '(' || s[i] == '[')
        {
            matching.push(s[i]);
        }
        else if (s[i] == ')' || s[i] == ']')
        {
            if (!matching.empty() && ((s[i] == ')' && matching.top() == '(') || (s[i] == ']' && matching.top() == '[')))
            {
                matching.pop();
                if (matching.empty())
                {
                    res += s.substr(start, i - start + 1);
                    start = i + 1;
                }
                else
                {
                    count++;
                }
            }
            else
            {
                appendRes(s, res, start, i - count * 2);
                res += s.substr(i - count * 2, count * 2);
                res += (s[i] == ')' ? "()" : "[]");
                start = i + 1;
                count = 0;
                while (!matching.empty())
                {
                    matching.pop();
                }
            }
        }
    }

    if (!matching.empty())
    {
        if (count > 0)
        {
            appendRes(s, res, start, s.size() - count * 2);
            res += s.substr(s.size() - count * 2, count * 2);
        }
        else
        {
            appendRes(s, res, start, s.size());
        }
    }

    cout << res << endl;

    return 0;
}
2025/1/28 16:02
加载中...