Q:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
注意:空字符串可被认为是有效字符串。
解法一:利用栈的知识,如果是左括号,入栈;如果是右括号,自爱栈不空的情况下,与栈顶元素比较,如果匹配则出栈。最后判断栈是否为空,如果为空,则全部匹配成功。
class Solution:
def isValid(self, s: str) -> bool:
s = s.lstrip(' ').rstrip(' ')
if s=='':
return True
if len(s)%2==1:
return False
ls = []
if s[0]=='}' or s[0]==']' or s[0]==')':
return False
else:
ls.append(s[0])
for i in range(1,len(s)):
if s[i] == '(' or s[i] == '[' or s[i] == '{':
ls.append(s[i])
if s[i] == ']' and len(ls) != 0:
if ls[len(ls)-1]=='[':
ls.pop()
elif s[i] == ')' and len(ls) != 0:
if ls[len(ls)-1]=='(':
ls.pop()
elif s[i] == '}' and len(ls) != 0:
if ls[len(ls)-1]=='{':
ls.pop()
if len(ls) == 0:
return True
else:
return False
解法二:利用Python中的replace函数
# 括号匹配
# 用replace把成对的括号替换为空
# 如果最后s不为空串,则不匹配
def isValid(s):
while '{}' in s or '[]' in s or '()' in s:
s = s.replace('()', '')
s = s.replace('[]', '')
s = s.replace('{}', '')
return len(s) == 0