Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

help "Runtime Error"

+1 vote
1,447 views

My code could work in visual studio, but leetcode report "Runtime Error Last executed input: "]" ".

    bool isValid(string s) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
   // s1 store (), s2 store [], s3 store {}
    stack<char> s1; stack<char> s2; stack<char> s3;
    for(int i=0;i<s.length();i++)
    {
        switch(s[i]){
            case '(':s1.push('(');break;
            case ')':if(s1.top()=='(')s1.pop();else return false;break;
            case '[':if(s1.empty())s2.push('[');else return false;break;
            case ']':if(s1.empty()&&s2.top()=='[')s2.pop();else return false;break;
            case '{':if(s1.empty()&&s2.empty())s3.push('{');else return false;break;
            case '}':if(s1.empty()&&s2.empty()&&s3.top()=='{')s3.pop();else return false;break;
            default: return false;
        }
    }
    if(s1.empty()&&s2.empty()&&s3.empty())return true;
    else return false;
}
asked Nov 26, 2013 in Valid Parentheses by wabcidf (310 points)

actually only one stack is enough

Hello .I am having trouble solving this problem . Can you share your one stack solution? Thank U so much.

1 Answer

+3 votes
 
Best answer

Because according to your conditional statement:

if(s1.empty()&&s2.top()=='[')

You are trying s2.top() when the s2 is empty, which caused the runtime error.

answered Nov 26, 2013 by 1337c0d3r (21,960 points)
selected Nov 26, 2013 by wabcidf

...