题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @return bool布尔型 # class Solution: def isValid(self , s: str) -> bool: # write code here stack = [] cmap = {")":"(", "]":"[", "}":"{"} # 键值对形式存储一对括号 for c in s: if c in ["(", "[", "{"]: # 左括号入栈 stack.append(c) elif c in [")", "]", "}"]: # 右括号不入栈 if not stack or stack[-1] != cmap[c]: return False stack.pop() # 若栈顶为右括号对应的左括号时就弹出左括号 return len(stack) == 0