LC 20有效的括号Valid Parentheses 简单
判断只含 '()[]{}' 的字符串 s 中括号是否全部按正确顺序闭合匹配。
思路 栈 + 右左映射:左括号入栈,右括号须匹配栈顶,栈空或不配即无效;结束时栈须为空。O(n)。
class Solution: def isValid(self, s: str) -> bool: pairs = {")": "(", "]": "[", "}": "{"} st = [] for c in s: if c in "([{": st.append(c) elif not st or st.pop() != pairs[c]: return False return not st