原题:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
解法一:(栈)
如果此时我们遍历的字符是括号的左半部分,那么将字符入栈,如果栈顶元素和此时遍历的元素正好组合成一个括号,则出栈。
最后如果栈为空则返回True,反之,返回False。
写法一:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
ans = []
if s =="":
return True
for i in range(0,len(s)):
if ans != []:
if ans[-1] == '(' and s[i] == ")":
ans.pop()
continue
elif ans[-1] == '{' and s[i] == "}":
ans.pop()
continue
elif ans[-1] == '[' and s[i] == "]":
ans.pop()
continue
ans.append(s[i])
if ans == []:
return True
else:
return False
写法二:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
ans = []
mapping ={")":"(","}":"{","]":"["} #创建字典
for char in s:
if char in mapping:
top_element = ans.pop() if stack else '#'
if mapping[char] != top_element:
return False
return not ans