Simple Python Solution


  • 0
    C

    The idea is :

    • if left paratheses: push into the stack
    • if right paratheses: pop the stack and compare

    Python Code:

    class Solution:
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            def isReverse(a, b):
                if(a=='('):
                    if(b==')'): return True
                    else: return False
                if(a=='['):
                    if(b==']'): return True
                    else: return False
                if(a=='{'):
                    if(b=='}'): return True
                    else: return False
            def isLeft(a):
                if((a=='(') or (a=='[') or (a=='{')): return True
                return False
            def isRight(a):
                if((a==')') or (a==']') or (a=='}')): return True
                return False
            if(s==""): return True
            if((len(s)%2)==1): return False
            if(not isLeft(s[0])): return False
            stack = []
            while(s):
                
                # Left, push into the stack
                if(isLeft(s[0])):
                    stack.append(s[0])
                    s = s[1:]
                    
                # Right, pop the stack and compare with the current
                elif(isRight(s[0])):
                    # try:
                    temp = stack.pop()
                    # except: return False
                    if(not isReverse(temp, s[0])):
                        return False
                    s = s[1:]
            if(stack==[]): return True
            return False
    

Log in to reply
 

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