Basic "0ms" C++ solution with stack


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

Log in to reply
 

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