LeetCode 筆記 - 20. Valid Parentheses

題目在此 20. Valid Parentheses

給定一個只有括號的字串,請判斷是否為合法結束的括號字串

解題思維

這題會用到 Stack 來處理這個問題

基本的思維是如果遇到左邊括號,那就放進 Stack
如果遇到右邊括號,那麼 Stack 裡面最新的元素應該要是相同類型的左邊括號

如果湊不起來,那就是不合法的括號字串

完成 🥰

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def isValid(self, s: str) -> bool:

stack = []

left = ['(', '{', '[']
right = [')', '}', ']']

for c in s:
if c in left:
stack.append(c)
elif c in right and stack:
if right.index(c) == left.index(stack[-1]):
stack.pop()
else:
return False
else:
return False

return not stack

相關文章