跳到主要内容

括号序列 [easy]

括号序列 [easy]

https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2?tpId=188&&tqId=36321&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列。

括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。

  • 示例1 输入
"["

返回值

false
  • 示例2

输入

"[]"

返回值

true

First Try

2020-11-09

本来还打算用计数法解决,但觉得思路有点乱,看到题目分类有个“栈”的标志,改为使用栈轻松解决,算是受到了提醒吧。

#
#
# @param s string字符串
# @return bool布尔型
#

from collections import Counter

class Solution:
def isValid(self , s ):
# write code here
mapping = {")": "(", "]": "[", "}": "{"}
stack = []
for idx, c in enumerate(s):
if c in ["(", "[" , "{"]:
stack.append(c)
elif c in [")", "]", "}"]:
if not len(stack):
return False
ch = stack.pop()
if ch not in mapping[c]:
return False
if len(stack):
return False
return True