Cpp solution 0ms with stack


  • 0
    D
    class Solution {
    public:
        bool isValid(string s) {
            stack<char> vars;
            bool push;
            if(s.size() % 2 != 0)
                return false;
            for(int i = 0; i < s.size();++i)
            {
                char in = s[i];
                char expect;
                push = false;
                switch(in)
                {
                    case '(':
                    case '{':
                    case '[':
                        vars.push(in);
                        push = true;
                        break;
                    case ')':
                        expect = '(';
                        break;
                    case '}':
                        expect = '{';
                        break;
                    case ']':
                        expect = '[';
                        break;
                    default:
                        return false;
                }
                if(!push)
                {
                    if(vars.empty())
                        return false;
                    if(vars.top() == expect)
                        vars.pop();
                    else
                        return false;    
                }
            }
            return vars.empty();
        }
    };

Log in to reply
 

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