Python solution beating 81.89%


  • 0
    K
    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            stack.append(s[0])
            for i in range(1,len(s)):
                if s[i] in ["[","(","{"]:
                    stack.append(s[i])
                else:
                    if len(stack) != 0:
                        p = stack.pop()
                    else:
                        stack.append(s[i])
                    if p + s[i] not in ["()","[]","{}"]:
                        return False
            if len(stack) == 0:
                return True
            else: 
                return False

  • 0
    J

    if p + s[i] not in ["()","[]","{}"]:
    #p may be None


  • 0
    K

    how? p is popped out from a nonempty stack which contains only [, ( or {


Log in to reply
 

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