Python版本暴力解法

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for c in s:
            if c == '(' or c == '[' or c == '{':
                stack.append(c)
            if stack != []:
                if stack[-1] == '(' and c == ')':
                    stack.pop(-1)
                elif stack[-1] == '[' and c == ']':
                    stack.pop(-1)
                elif stack[-1] == '{' and c == '}':
                    stack.pop(-1)
                elif ((stack[-1] == '(') and (c in "]}")) or \
                     ((stack[-1] == '[') and (c in ")}")) or \
                     ((stack[-1] == '{') and (c in ")]")):
                    return False
            else: # 起始符号不是 ([{ 之一,必不是有效括号序列
                return False
        if not stack:
            return True
        else:
            return False

Python版本优化解法

class Solution:
    def isValid(self, s: str) -> bool:
        if len(s)%2 == 1:
            return False
        stack = []
        par_map = {')': '(', ']': '[', '}': '{'}
        for c in s:
            if c not in par_map:
                stack.append(c)
            elif not stack or par_map[c] != stack.pop():
                return False
        return not stack