iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

LeetCode 每日一題挑戰系列 第 16

Day 16 - Valid Parentheses

  • 分享至 

  • xImage
  •  

題目

給定一個只包含 (、)、{、}、[、] 的字串 s,判斷它是否是一個「有效的括號字串」。

規則:

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

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

每個右括號都必須對應到一個有效的左括號。

範例

Input: s = "()"
Output: true

Input: s = "()[]{}"
Output: true

Input: s = "(]"
Output: false

Input: s = "([])"
Output: true

Input: s = "([)]"
Output: false

Constraints

1 <= s.length <= 10^4

s 只包含 '()[]{}'

解題思路

這題的關鍵在於「括號配對」問題,非常適合用 Stack(堆疊) 來處理。

流程:

遍歷字串,遇到左括號就丟進堆疊。

遇到右括號時,檢查堆疊頂端是否是對應的左括號。

如果堆疊空了,或是對不上,就直接回傳 false。

最後檢查堆疊是否為空,如果還有多的左括號,代表不合法。

程式碼(Java)
import java.util.*;

class Solution {
public boolean isValid(String s) {
Stack stack = new Stack<>();

    for (char c : s.toCharArray()) {
        if (c == '(') {
            stack.push(')');
        } else if (c == '{') {
            stack.push('}');
        } else if (c == '[') {
            stack.push(']');
        } else {
            if (stack.isEmpty() || stack.pop() != c) {
                return false;
            }
        }
    }
    
    return stack.isEmpty();
}

}

心得

這題很經典,幾乎每個刷題新手都會遇到。
雖然看起來簡單,但其實藏著一個重點:用堆疊可以讓「後進先出」的結構自然對應括號配對問題。

另外一個小技巧:我直接在 push 的時候推「期望的右括號」,這樣在遇到右括號時就能直接比較,程式碼會更簡潔。https://ithelp.ithome.com.tw/upload/images/20250926/20169537CbopHoFiVQ.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/20169537BxarSpXqb6.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/20169537VmRxOvslwV.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/201695372BNtYjEMR3.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/20169537u7cDIwmI6g.pnghttps://ithelp.ithome.com.tw/upload/images/20250926/20169537wuB29uXbaJ.png


上一篇
Day 15 - 4Sum
下一篇
Day 17 - Generate Parentheses
系列文
LeetCode 每日一題挑戰20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言