Short and clean Python solution. No messy multiple "if"s


  • 1
    V

    The difference of this code from most others is the use of LEFT and RIGHT constants. So we can check the matching parentheses by just checking the index.

    LEFT = '([{'
    RIGHT = ')]}'
    
    class Solution:
        def isValid(self, s):
            brackets = []
            for c in s:
                i = LEFT.find(c)
                if i != -1:
                    brackets.append(i)
                elif not brackets or RIGHT[brackets.pop()] != c:
                    return False
            return not brackets
    

Log in to reply
 

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