方法一、栈
一、利用栈先入后出的特点,如果遇到左括号入栈,遇到右口号时将对应栈顶左括号出栈,则遍历完所以的括号后stack
仍为空。
二、建立哈希表pairs
构建左右括号的对应关系。
Python3 代码解释
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
pairs = {
"}": "{",
"]": "[",
")": "(",
}
stack = list()
for i in s:
if i in pairs:
if not stack or stack[-1] != pairs[i]:
return False
stack.pop()
else:
stack.append(i)
return not stack
![](https://blog.liuyingjie.com.cn/wp-content/uploads/2023/07/20.有效的括号.png)
Source: LeetCode(The title reproduced in this blog is for personal study use only)
Be First to Comment