检查平衡分组字符时在线判断运行时错误

Pra*_*eep 1 c++ stack runtime-error

这是我的代码,用于检查一组分组字符是否正确平衡.它在我的本地机器上工作正常,但在线判断给我一个运行时错误.

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

bool balanced(string exp)
{
    stack<char> st;
    int i;
    for(i=0;i<exp.length();i++)
    {
            if(exp[i]== '{' || exp[i]=='[' || exp[i]== '(') st.push(exp[i]);
            else if(exp[i]=='}'){
                if(st.top() == '{' && !st.empty()) st.pop();
                else return false;
            }
            else if(exp[i]==')'){
                if(st.top() == '(' && !st.empty()) st.pop();
                else return false;
            }
            else if(exp[i]==']'){
                if(st.top()=='['  && !st.empty()) st.pop();
                else return false;
            }
    }
    if(st.empty())return true;
    else return false;
}

int main() {
    string exp;int n;
    cin >> n;
    cin.ignore();
    while(n--)
    {
        getline(cin,exp);
        bool balance = balanced(exp);
        if(balance == true)cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

200*_*ess 5

if(st.top() == '{' && !st.empty())
Run Code Online (Sandbox Code Playgroud)

在进入顶部之前,您应该检查堆栈空虚.

if(!st.empty() && st.top() == '{')
Run Code Online (Sandbox Code Playgroud)