难度:简单
题目描述:
思路总结:我自己用栈实现了一种解法,遇到了两个小坑,属于做题熟练后自然而然可以解决的小问题。
题解一:
class Solution:
def isValid(self, s: str) -> bool:
#这题熟悉的面孔,一个简单的解法:栈
if s == "":return True
n = len(s)
stack = []
l2r = {"(":")", "[":"]", "{":"}"}
i = 0
while i < n:
if s[i] in l2r:
stack.append(s[i])
else:
#坑1:stack如果为空,会报错
if stack == [] or s[i] != l2r[stack.pop()]:return False
i += 1
if stack != []:return False #坑2:如果stack里面还有剩余的元素,解答出错
return True
#思路不变,改进代码写法
class Solution:
def isValid(self, s: str) -> bool:
#这题熟悉的面孔,一个简单的解法:栈
if s == "":return True
n = len(s)
if n%2 != 0:return False
stack = ["?"]
l2r = {"(":")", "[":"]", "{":"}", "?":"?"}
for c in s:
if c in l2r:stack.append(c)
elif c != l2r[stack.pop()]:return False
return len(stack)==1