iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
自我挑戰組

leetcode系列 第 20

leetcode 20. Valid Parentheses

  • 分享至 

  • xImage
  •  

題目:
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
給定一個s僅包含字元'('、')'、'{'、和 的字串'}',確定輸入字串是否有效。'['']'

如果滿足以下條件,則輸入字串有效:

左括號必須由相同類型的括號封閉。
左括號必須依照正確的順序閉合。
每個右括號都有一個與之對應的同類型的左括號。
題目說明

給定一個只包含字元 '(' , ')' , '{' , '}' , '[' , ']' 的字串,判斷輸入字串是否為 有效的括號。

規則:

左括號必須由相同型別的右括號關閉。

左括號必須以正確的順序關閉。

例如:

輸入:"()" → 輸出:true

輸入:"()[]{}" → 輸出:true

輸入:"(]" → 輸出:false

輸入:"([)]" → 輸出:false

輸入:"{[]}" → 輸出:true
https://ithelp.ithome.com.tw/upload/images/20251004/20169340a6p6iDw7vQ.png
解題思路

這題可以用 堆疊 (Stack) 來解決:

遍歷字串中的每個字元:

如果是左括號 (、{、[,就壓入堆疊。

如果是右括號 )、}、],檢查堆疊頂部:

堆疊為空 → 無效(false)。

堆疊頂部不匹配 → 無效(false)。

匹配 → 彈出堆疊頂部。

遍歷完成後,如果堆疊是空的 → 有效;否則 → 無效。


上一篇
leetcode 19. Remove Nth Node From End of List
系列文
leetcode20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言