gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:50 26 4
gpt4 key购买 nike

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

#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;
}

最佳答案

if(st.top() == '{' && !st.empty())

您应该在取顶之前检查堆栈是否为空。

if(!st.empty() && st.top() == '{')

关于c++ - 检查平衡分组字符时在线判断运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34359422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com