Problem: 20. 有效的括号
思路
1.定义栈存储输入的括号数据
2.定义字典存储括号数据,用于匹配栈中存储数据
3.检验栈中数据,验证dict条件:当前key是否存在
4.存在后,获取栈底数据,与字典的右括号做匹配,匹配成功,删除栈中数据
5.栈为空时,添加数据直到遍历完毕
6.返回栈中结果
解题方法
使用栈的来处理当前问题
复杂度
- 时间复杂度:
添加时间复杂度, O(n)
- 空间复杂度:
添加空间复杂度, O(n)
Code
Python
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dic = {')':'(',']':'[','}':'{'}
stack = []
for i in s:
if stack and i in dic:
if stack[-1] == dic[i]:
stack.pop()
else:
return False
else:
stack.append(i)
return not stack