这是我的代码,用于检查一串分组字符是否正确平衡。它在我的本地计算机上运行良好,但是在线判断给我一个运行时错误。
#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() == '{')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句