题目概述:
题目注意点:
初始化最好有个占位符
解题思路:
- 建立堆栈,这里使用列表
- 只存储左边的括号,遇到配对的就出栈
- 当最后只剩下标志符的时候,说明正确
完整代码:
class Solution:
def isValid(self, s: str) -> bool:
dic = {'{': '}', '[': ']', '(': ')', '?': '?'}
stack = ['?'] # 初始化,防止出现删除出错的情况
for c in s:
if c in dic: stack.append(c)
elif dic[stack.pop()] != c: return False
return len(stack) == 1
作者:jyd
链接:https://leetcode-cn.com/problems/valid-parentheses/solution/valid-parentheses-fu-zhu-zhan-fa-by-jin407891080/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。