在平衡括号代码中出现运行时错误

getting runtime error in balanced parenthesis code

这是我为解决平衡括号问题而编写的代码,但我遇到了一些隐藏测试用例的运行时错误,而且我无法找到错误的地方? 任何人都可以帮我找出这段代码中的错误以及为什么它会给我运行时错误吗?

查找平衡括号的函数我写的如下..

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