Search code examples
c++stackruntime-errorparentheses

getting runtime error in balanced parenthesis code


this is the code I have written to solve balanced parenthesis problem but I am getting runtime error for some hidden test cases and I am unable to find where it is wrong? can anyone help me find what is wrong in this code and why it is giving me runtime error?

function to find balanced parenthesis I have written as follow..

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

Solution

  • If you have just ")" (or "]", "}") string as input, you will try to pop an empty stack.

    int main() {
        std::string demo = ")";
        std::cout << ispar(demo) << std::endl;
    }
    

    demo : https://wandbox.org/permlink/XgurahYzZY5KIV9U


    It usually a good practice to create small test when you code, even better, create your test before the function.

    More info : Tdd