11 lines C++ stack


  • 0
    class Solution {
    public:
        bool isValid(string s) {
            stack<char>stk;
            for(auto c: s){
                if(stk.empty() && (c == ')' || c == ']' || c == '}')) return false;
                if(c == '(' || c == '[' || c == '{') stk.push(c);
                else{
                    char left = stk.top();
                    if((c == ')' && left != '(') || (c == ']' && left != '[') || (c == '}' && left != '{')) return false;
                    stk.pop();
                }
            }
            return stk.empty();
        }
    };
    

Log in to reply
 

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