Simple and readable python solution.


  • 0
    W

    This is my python solution.

    class Solution:
        # @return a boolean
        def isValid(self, s):
            if not s:
                return True
            else:
                result = ['[]', '{}', '()']
                parentheses = []
                for i in s:
                    # if the char is '(', '[', or '{', put it into the list
                    if i in '{([':
                        parentheses.append(i)
                    else:
                        # if the list is empty and the input is ')', ']', or '}', the result is false
                        if len(parentheses) == 0:
                            return False
                        # pop from the list, combine the element with input, then decide whether the combination is in result list
                        tmp = parentheses.pop() + i
                        if tmp not in result:
                            return False
                # if the list is empty, the result is true
                if not parentheses:
                    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.