Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}"
Output: true
class Solution:
# @return a boolean
def isValid(self, s):
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
ps:自己想的超级超级麻烦,然而看到有人用栈实现,还这么简洁,超级赞!
本文介绍了一种使用栈数据结构高效验证括号字符串有效性的方法。通过遍历输入字符串,利用栈来跟踪开括号,确保每种类型的括号正确闭合且顺序无误。文章附带Python代码示例,展示了如何实现这一算法。

191

被折叠的 条评论
为什么被折叠?



