题目:
有效的括号: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例:
输入: "()", 输出: true
输入: "()[]{}", 输出: true
输入: "(]", 输出: false
输入: "([)]", 输出: false
输入: "{[]}", 输出: true
--------------------------------------------------------------------------
解法1:对字符串进行循环替换,将所有成对的括号替换成空字符。就是效率偏低。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
# 如果长度为奇数,返回False
if len(s) % 2 == 1:
return False
for i in range(len(s)):
s = s.replace("()", "").replace("[]", "").replace("{}", "")
if len(s) > 0:
return False
else:
return True
return True
解法2:巧用字典和栈
解法逻辑:
先用字典 “反向存储” 括号字符对,eg. {")":"("}。
如果在stack中,存在"("(此时stack中有2个元素 [None,"("],长度为2),同时s的下一个字符是")"时,那么就从stack中剔除"(",stack只剩下[None],长度为1。
但如果在stack中,存在")",此时stack中有2个元素 [None,")"],长度为2),同时s的下一个字符是")"时,那么就在stack中添加一个"(",此时stack为[None, ")", "("], 长度为3。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
# 如果长度为奇数,返回False
if len(s) % 2 == 1:
return False
# 用字典 “反向存储” 括号字符
dic = {")": "(", "]": "[", "}": "{"}
stack = [None]
for S in s:
if S in stack and dic[S] == stack[-1]:
stack.pop()
else:
stack.append(S)
return len(stack) == 1
参考: