题目描述:
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true``
这个其实是比较熟悉的一道题目了,基本都是用栈来解决,python中栈就用列表来,这里还用上了字典,相应的括号组成相应的键值对即可
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
dic = {'(':')','{':'}','[':']','?':'?'} # 加上问号键值对是为了防空
stack = ['?']
for i in s:
if i in dic: # 遍历字典中的键值,为键值则入栈
stack.append(i)
elif dic[stack.pop()] != i: # 遇到右括号就出栈一个并判断是否是配对的括号
return False # 不是则返回false
return len(stack) == 1
但是我还在题解中看到一种解法,虽然效率不是很高,但我感觉角度很好玩,这里也附上:
class Solution:
def isValid(self, s):
s_new = s.replace('()','').replace('[]','').replace('{}','')
while len(s_new) < len(s):
s = s_new
s_new = s.replace('()','').replace('[]','').replace('{}','')
return not s_new