2025/3/3 【栈与队列】LeetCode 20.有效的括号 【√】
My method:用两个栈解决
class Solution: def isValid(self, s: str) -> bool: stack = [] for char in s: stack.append(char) n = len(stack) if(n % 2 != 0): return False temp = [] for i in range(n): char = stack.pop() if char == ')': temp.append('(') elif char == '}': temp.append('{') elif char == ']': temp.append('[') elif char == '(': if not temp or temp.pop() != char: return False elif char == '{': if not temp or temp.pop() != char: return False elif char == '[': if not temp or temp.pop() != char: return False return not temp
方法2:只用一个栈解决
从前到后遍历字符串
class Solution: def isValid(self, s: str) -> bool: stack = [] for item in s: if item == '(': stack.append(')') elif item == '[': stack.append(']') elif item == '{': stack.append('}') elif not stack or stack[-1] != item: return False else: stack.pop() return True if not stack else False
方法3:使用字典+栈
写这个方法只是为了熟悉字典的操作。括号匹配是使用栈解决的经典问题。
class Solution: def isValid(self, s: str) -> bool: stack = [] mapping = { '(': ')', '[': ']', '{': '}' } for item in s: if item in mapping.keys(): stack.append(mapping[item]) elif not stack or stack[-1] != item: return False else: stack.pop() return True if not stack else False