问题描述
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.
给定一个只包含字符'(',')','{','}','['和']'的字符串,判断输入字符串是否有效。
输入字符串是有效的,如果:
- 开括号必须由相同类型的括号括起。
- 开括号必须按正确的顺序闭合。
注意,空字符串也被认为是有效的。
输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "(]"
输出: false
输入: "([)]"
输出: false
输入: "{[]}"
输出: true
Python 实现
实现一:判断括号的有效性,最直接的方法就是使用栈,出现左括号时入栈,出现右括号时,栈顶必须是对应的左括号并弹出,不然返回 False,最后栈的大小为 0,则说明括号有效。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if len(stack) > 0 and stack[-1] == '(' and c == ')':
stack.pop()
elif len(stack) > 0 and stack[-1] == '{' and c == '}':
stack.pop()
elif len(stack) > 0 and stack[-1] == '[' and c == ']':
stack.pop()
else:
stack.append(c)
if len(stack) == 0:
return True
else:
return False
实现二:原理跟上面一样,只是通过字典将每组括号对储存起来,这样写的代码更便于拓展和维护,可读性也更强。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pairs = {"(": ")", "{": "}", "[": "]"}
stack = []
for i in range(len(s)):
if s[i] in pairs:
stack.append(s[i])
elif len(stack) > 0 and s[i] == pairs[stack[-1]]:
stack.pop()
else:
return False
if len(stack) == 0:
return True
else:
return False

本文介绍了一种使用栈数据结构来判断括号序列是否有效的方法。通过两种实现方式,一种是直接比较括号类型,另一种是利用字典提高代码可读性和可维护性。文章详细解释了算法的运行逻辑,并提供了Python代码示例。
1518

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



