示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
法一:最容易想到的是利用堆栈,先检索遇到左括号push;如果不是左括号,先判断是否有左括号(栈非空)否则返回Fals,判断右括号和栈顶元素是否配对,配对就pop,否则就返回Fals;最后返回还要检查栈非空和是否成对
python
class Solution:
def isValid(self, s: str) -> bool:
length=len(s)
if length%2 !=0:
return False
else:
s1=[]
count=0
for i in range(length):
if s[i] in "({[":
s1.append(s[i])
else:
if not s1:
return False
if s[i]==")" and s1[-1]=="(":
count+=1
elif s[i]=="]" and s1[-1]=="[":
count+=1
elif s[i]=="}" and s1[-1]=="{":
count+=1
else:
return False
s1.pop()
return not s1 and count==length//2