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)
Run Code Online (Sandbox Code Playgroud)if(st.top() == '{' && !st.empty())
在进入顶部之前,您应该检查堆栈空虚.
if(!st.empty() && st.top() == '{')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |