20. 有效的括号(Easy)
# 题目描述
给定三种括号对:{}
,[]
,()
。判断括号是否是有效的,即括号必须是成对出现的。
# 样例
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
1
2
3
4
5
2
3
4
5
# 题目解析
栈的经典问题
# 代码
class Solution:
def isValid(self, s: str) -> bool:
mappings = {'{': '}', '[': ']', '(': ')'}
stack = []
for char in s:
if char in mappings:
stack.append(mappings[char])
else:
if not stack or stack.pop() != char: # 出现匹配错误
return False
return len(stack) == 0 # 可能还有剩余的,这里比较容易漏掉
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2022/10/25, 02:40:54