60分求调,无栈纯暴力,已老实

P1241 括号序列

flashfear @ 2024-11-19 20:06:07

#include <bits/stdc++.h>

using namespace std;

void dispose(char c) {
    if (c == '[' || c == ']')
        cout << "[]";
    else if (c == '(' || c == ')')
        cout << "()";
}

int main() {
    string str;
    getline(cin, str);
    vector<int> vc1(str.size(), 0);
    vector<char> vc2(str.size());
    for (int i = 0; i < str.size(); i++) {
        if (str[i] == '[' || str[i] == '(') vc2[i] = 'z';
        if (str[i] == ']' || str[i] == ')') vc2[i] = 'y';
    }

    for (int i = 0; i < str.size(); i++) {
        if (vc2[i] == 'y') {
            for (int j = i; j >= 0; j--){
                if (vc2[j] == 'z' && vc1[j] == 0) {
                    if (str[i] == ']' && str[j] == '[' || str[i] == ')' && str[j] == '(') {
                        vc1[i] = vc1[j] = 1;
                        break;
                    }
                }
            }
        }
    }

    for (int i = 0; i < str.size(); i++) {
        if (vc1[i] == 0) {
            dispose(str[i]);
            continue;
        }
        cout << str[i];
    }

    system("pause");
    return 0;
}

by flashfear @ 2024-11-19 21:07:22

已解决,把break往外拉一层即可食用。

考察它与它左侧离它最近的未匹配的的左括号,如果左侧未匹配的左括号不存在或与之不对应,则其配对失败。

失败后不再检索。

警示后人(悲)


|