问题描述
这是我为解决括号平衡问题而编写的代码,但是我遇到了一些隐藏测试用例的运行时错误,我无法找到错误的地方? 谁能帮我找出这段代码有什么问题,为什么会出现运行时错误?
找到平衡括号的函数我写如下..
bool ispar(string x)
{
stack<char> s;
for(auto i:x)
{
if(i=='(')
{
s.push('(');
}
else if(i=='{')
{
s.push('{');
}
else if(i=='[')
{
s.push('[');
}
else if(i==')' && s.top()=='(')
{
s.pop();
}
else if(i=='}' && s.top()=='{')
{
s.pop();
}
else if(i==']' && s.top()=='[')
{
s.pop();
}
}
if(s.empty())
return true;
else
return false;
}
解决方法
如果您只有 ")"
(或 "]"
,"}"
)字符串作为输入,您将尝试弹出一个空堆栈。
int main() {
std::string demo = ")";
std::cout << ispar(demo) << std::endl;
}
演示:https://wandbox.org/permlink/XgurahYzZY5KIV9U
在编写代码时创建小测试通常是一个好习惯,更好的是,在函数之前创建测试。
更多信息:Tdd