题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个有小、中、大括号的六个符号组成的字符串,如果其中所有的括号都能正确配队,那么算有效,否则无效。

思路分享

  • 基本逻辑肯定涉及到了栈,但如何应用有好几种不同方法。

  • 下面的参考题解就是最普通的一种,在栈有元素且新元素为括号右侧的情况下,判断是否出栈,最终栈空代表有效。

  • 但其实还有其它的不错思路,比如遍历到括号左侧,就入栈对应的括号右侧,这样就把问题转换成了消除字符串相邻的元素;或者用哈希表存储括号右侧对应的左侧符号与栈顶是否一致……

    https://leetcode.cn/problems/valid-parentheses/solutions/2809539/gua-hao-xiao-xiao-le-san-chong-li-yong-z-2xb3/

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def isValid(self, s: str) -> bool:
res = True
stk = list()
# print(ord(')')-ord('('))
# print(ord(']')-ord('['))
# print(ord('}')-ord('{'))
for c in s:
if stk:
if c == ')':
if ord(c) - ord(stk[-1]) == 1:
stk.pop()
else:
res = False
break
elif c == ']' or c == '}':
if ord(c) - ord(stk[-1]) == 2:
stk.pop()
else:
res = False
break
else:
stk.append(c)
else:
stk.append(c)

return res and not stk