Unique, concise, and most comprehensible solution


  • 0
    D

    Instead of pushing the actual opening brace to the stack, just push its corresponding closing symbol instead and check that against the next closing brace.

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> sds;
            for (int i = 0; i < s.size(); ++i) {
                if      (s[i] == '(') sds.push(')');
                else if (s[i] == '{') sds.push('}');
                else if (s[i] == '[') sds.push(']');
                else {
                    if (sds.empty() || sds.top() != s[i])
                        return false;
                    sds.pop();
                }
            }
            return sds.empty();
        }
    };
    

Log in to reply
 

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