题目描述
给出一个仅包含字符’(‘,’)‘,’{‘,’}‘,’[‘和’]',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。
数据范围:字符串长度 0≤n≤10000
要求:空间复杂度 O(n),时间复杂度 O(n)
示例1
输入:
“[”
复制
返回值:
false
复制
示例2
输入:
“[]”
复制
返回值:
true
code
class Solution:
def isValid(self , s: str) -> bool:
# write code here
d={'}':'{',"]":"[",")":"("}
stack=[]
for char in s:
if char in"{[(":
stack.append(char)
if char in "}])":
if not stack:
return False
else:
if d[char]==stack[-1]:
stack.pop()
else:
return False
return not stack