Grind 75 Python 做題記錄 20. Valid Parentheses
Grind 75 Python 做題記錄 20. Valid Parentheses
class Solution:
def isValid(self, s: str) -> bool:
# 若為空字串直接返回
if len(s) == 0: return True
# 建立括弧對的紀錄
pari_dict:dict = {
")":"(",
"}":"{",
"]":"["
}
# 建立 stack
stack = list()
# 遍歷字串
for char in s:
# 假如是右括號
if char in pari_dict:
# 若字串尚未結束,但 pop 為 0 回傳 False
if len(stack) == 0: return False
# 確認是否有對應左括號在 stack 中,若無法對上,就回傳 False
if stack.pop() != pari_dict[char]: return False
# 左括號的情況
else:
# 放入 stack
stack.append(char)
# 假如最後 Stack 為空,則回傳 True
if len(stack) == 0:
return True
else:
return False
口訣
括弧字典k與v,右括為k左括v
建立stack存左括,遍歷字串為字元
遇右括號先判斷,stack空回傳False
如不空則pop出來,比對字典k與v
遇左括號放stack,迴圈結束看stack
stack空則回傳True,stack不空則False