Help "Runtime Error"


  • 1
    W

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

  • 3

    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.


  • 0
    W

    actually only one stack is enough


  • 0
    W

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


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.