class Solution: def isValid(self , s: str) -> bool: # write code here stack = [] match = {')':'(', ']':'[', '}':'{'} for c in s: # c是左括号,入栈 if c in match.values(): stack.append(c) # c是右括号,判断栈是否为空,如果为空则不合法,不为空则比较c与栈顶元素 elif c in match.keys(): try: if stack[-1] == match.get(c): stack.pop() else: # 只要有一个不匹配就不需要再比 return False except: # 如果stack[-1]报错,表示stack为空,此时遇到右,不合法 return False if stack: return False else: return True