C++, Python Solutions. O(n) runtime, O(n) space.


  • 0

    C++

    bool isValid(const string& s) {
        stack<char> st;
        for(const char& c : s) {
            if(c == '(')
                st.push(')');
            else if(c == '{')
                st.push('}');
            else if(c == '[')
                st.push(']');
            else {
                if(st.empty() || st.top() != c)
                    return false;
                st.pop();
            }
        }
        return st.empty();
    }
    

    Python

    def isValid(self, s):
        st = []
        for c in s:
            if c == '(':
                st.append(')')
            elif c == '{':
                st.append('}')
            elif c == '[':
                st.append(']')
            elif not st or st.pop() != c:
                return False
        return not st
    

Log in to reply
 

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