Standard Solution with Python ( Beat over 99%)


  • 0
    J
    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            length = len(s)
            if(length % 2):
                return False
            
            for c in s:
                if(not stack):
                    stack.append(c)
                    continue
                top = stack[-1]
                if(top == '('):
                    if(c == ')'):
                        stack.pop()       
                    else:
                        stack.append(c)
                elif(top == '['):
                    if(c == ']'):
                        stack.pop()       
                    else:
                        stack.append(c)
                elif(top == '{'):
                    if(c == '}'):
                        stack.pop()       
                    else:
                        stack.append(c)
                else:
                    return False
            if(not stack):
                return True
            else:
                return False
    

Log in to reply
 

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