44求调!
查看原帖
44求调!
1506652
guangyiliushan楼主2025/1/22 11:49

#1#2#4#6#12# 过了

#3#5#7#8#9#10 RE

#11 WA

#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] == '(')
        {
            matching.push(s[i]);
        }
        else if (s[i] == ')')
        {
            if (matching.top() == '(')
            {
                matching.pop();
                if (matching.empty() && i != 0)
                {
                    res += s.substr(start, i - start + 1);
                    start = i + 1;
                }
                else
                {
                    count++;
                }
            }
            else
            {
                appendRes(s, res, start, i-count*2);
                res += "()";
                start = i + 1;
                if(count>0) {
                    res += s.substr(i - count*2, count*2);
                    count = 0;
                }
            }
        }
        else if (s[i] == '[')
        {
            matching.push(s[i]);
        }
        else if (s[i] == ']')
        {
            if (matching.top() == '[')
            {
                matching.pop();
                if (matching.empty() && i != 0)
                {
                    res += s.substr(start, i - start + 1);
                    start = i + 1;
                }
                else
                {
                    count++;
                }
            }
            else
            {
                appendRes(s, res, start, i-count*2);
                res += "[]";
                start = i + 1;
                if(count>0) {
                    res += s.substr(i - count*2, count*2);
                    count = 0;
                }
            }
        }
    }

    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/22 11:49
加载中...