原题目
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: trueExample 2:
Input: "()[]{}" Output: trueExample 3:
Input: "(]" Output: falseExample 4:
Input: "([)]" Output: falseExample 5:
Input: "{[]}" Output: true
思路
边界条件:输入字符串为 0 也是有效括号
用堆栈存储,后一个和前一个匹配弹出前一个,不匹配压入后一个,遍历完字符串后堆栈深度为 0 就是有效括号,否则无效。
第一遍解法
# O(n) S(n)
# Runtime: 36 ms, faster than 90.35% of Python3
# Memory Usage: 13.2 MB, less than 33.79% of Python3
class Solution:
def isValid(self, s):
if len(s) == 0:
return True
d = {'(':-1, ')':1, '[':-2, ']':2, '{':-3, '}':3}
stack = []
for i in range(len(s)):
if len(stack) == 0:
stack.append(s[i])
else:
if d[s[i]] + d[stack[-1]] == 0:
stack.pop()
else:
stack.append(s[i])
return len(stack) == 0
第二遍解法
class Solution:
def isValid(self, s):
d = {'[':']', '{':'}', '(':')'}
stack = []
for ch in s:
if ch in d.values():
if len(stack) == 0:
return False
if stack[-1] == ch:
stack.pop()
else:
return False
if ch in d.keys():
stack.append(d[ch])
return len(stack) == 0
网上好的解法
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 == []
自己可以改进的地方
# 用dict存储对应的匹配括号
d = {'[':']', '{':'}', '(':')'}
# 第二遍解法两个return False优化
if stack == [] or dict[char] != stack.pop()
# list pop()方法用作比较时也会弹出
# 没有考虑其他字符的情况
else:
# len(stack) == 0 等价于 stack == []
最简代码
class Solution:
def isValid(self, s):
d = {'[':']', '{':'}', '(':')'}
stack = []
for ch in s:
if ch in d.keys():
stack.append(d[ch])
elif ch in d.values():
if stack == [] or ch != stack.pop():
return False
else:
return False
return stack == []
获得的思考
- 括号匹配本质上还是堆栈问题,对堆栈的操作是基础
- 在这个问题中,应通过实际情况排除不可能的情况节省时间复杂度,而这个需要具体问题具体分析,反过来考虑不成立的情况的种类
博客围绕括号匹配问题展开,给出原题目,判断输入字符串是否为有效括号。思路是用堆栈存储,匹配则弹出,不匹配则压入,遍历完后堆栈深度为 0 则有效。还提及多遍解法、可改进之处等,指出该问题本质是堆栈问题,要结合实际排除不可能情况。

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



