Python one pass with a stack


  • 1
    class Solution(object):
        def isValid(self, s):
            stack = []
            for c in s:
                if c == '[' or c == '{' or c == '(':
                    stack.append(c)
                elif ( c == ')' and (stack and stack[-1] == '(') ) or ( c== '}' and (stack and stack[-1] == '{') ) or ( c == ']' and (stack and stack[-1] == '[') ):
                    stack.pop()
                else:
                    return False
            return stack == []
    

Log in to reply
 

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