20 有效的括号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
def isValid(self, s: str) -> bool:
stack = ["sentry"] # 添加哨兵
top = 1
for i in s:
if stack[top-1] == "(" and i == ")":
stack.pop()
top -= 1
continue
elif stack[top-1] == "[" and i == "]":
stack.pop()
top -= 1
continue
elif stack[top-1] == "{" and i == "}":
stack.pop()
top -= 1
continue
stack.append(i)
top += 1
print(top, stack[top-2],stack[top-1])
if top == 1:
return True
else:
return False