Python Solution With Sets

  • 0
        def isValid(self, s):
            :type s: str
            :rtype: bool
            matching = set([('(', ')'), ('[', ']'), ('{', '}')])
            opening = set(['(', '[', '{'])
            brackets = []
            if len(s)%2 == 1:
                return False
            for paren in s:
                if paren in opening:
                    if brackets:
                        popped = brackets.pop()
                        if (popped, paren) not in matching:
                            return False
                        return False
            if len(brackets) != 0:
                return False
            return True```
    The code uses sets to keep track of the matching parentheses and uses a stack called brackets to ensure that every closing parentheses has a valid opening one.

Log in to reply

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