Short Python solution, 33ms beats 98%


  • 0
    P

    Works by essentially simulating a PDA of this language. Open parentheses cause a push to the stack, close parentheses cause a pop. At the end of the script state should be empty since our pushes should match our pops for valid strings.

    def isValid(self, s):
        parens = "({[)}]"
        state = []
        for c in s:
            i = parens.index(c)
            if i<3: state.append(i)
            elif not state or state.pop() != i-3: return False
        return not state
    

Log in to reply
 

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