Easy python solution using lists


  • 0
    class Solution:
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            lastopen = list()
            if(  (len(s)%2) != 0  ):
                return False
    
    
            for i in range(len(s)):
    
              #Add every opening brace to your stack 
                if(s[i] == '('):
                    lastopen.append('(')
                elif(s[i] == '{'):
                    lastopen.append('{')
                elif(s[i]=='['):
                    lastopen.append('[')
               #Each time you encounter a closing brace you pop from the stack only if the last element 
               #in the stack contains the corresponding brace (since you're popping make sure to check your lengths
                elif(s[i] == ')' ):
                    if( len(lastopen)>0 and  '(' == lastopen[-1] ):
                        lastopen.pop()
                    else:
                        return False
                elif(s[i] == ']' ):
                    if(len(lastopen)>0 and '[' == lastopen[-1] ):
                        lastopen.pop()
                    else:
                        return False
                elif(s[i] == '}' ):
                    if(len(lastopen)>0 and '{' == lastopen[-1] ):
                        lastopen.pop()
                    else:
                        return False
                       
            #If this was a valid solution you must've popped out all the opening braces
            if(len(lastopen) != 0):    
                return False
            
            return True
    

Log in to reply
 

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