求助,76分剩三个re

P1241 括号序列

GPA0 @ 2023-01-11 18:46:09

Runtime Error. Received signal 11: Segmentation fault with invalid memory reference.

#include<stack>
#include<iostream>
#include<string>
using namespace std;

void mate(char c,stack<int> &st2,stack<char> &st1,int pos,bool *a) {
    if(!st1.empty() && !st2.empty() && (c == ']' && st1.top() == '[') || (c == ')' && st1.top() == '(')) {
        st1.pop();          //弹出已储存的左括号 
        a[pos] = a[st2.top()] = true;       //将已匹配的括号标记 
        st2.pop();          //弹出已储存的左括号位置 
    }
}

int main() {
    string s;
    cin >> s;
    int l = s.length() ;
    bool *a = new bool[l];
    stack<char> stleft;     //储存左括号 
    stack<int> st2;         //储存左括号的位置 
    for(int i = 0; i < l; i++) {
        if(s[i] == '[' || s[i] == '(') {
            stleft.push(s[i]);
            st2.push(i);
        } else if(s[i] == ']' || s[i] == ')') {
            mate(s[i],st2,stleft,i,a);      //匹配左括号 
        }
    }

    for(int i = 0; i < l ; i++) {       //输出括号 
        if(a[i] == false && s[i] == ']') {
            cout << '[';
            cout << s[i];
        } else if(a[i] == false && s[i] == ')') {
            cout << '(';
            cout << s[i];
        } else if(a[i] == false && s[i] == '[') {
            cout << s[i];
            cout << ']';
        } else if(a[i] == false && s[i] == '(') {
            cout << s[i];
            cout << ')';
        } else if(a[i] == true)
            cout << s[i];

    }
}

by ___A__ @ 2023-02-04 11:36:56

栈为空的时候不可以弹出


|