Easy草稿★★★★★O(n) 時間 · O(1) 空間
StringHash TableCounting
Patterns#️⃣ 雜湊
尚未複習過

解法已隱藏 — 先讀題目敘述、自己想想看,再點上方按鈕揭曉。

1189Maximum Number of BalloonsArrays & HashingEasyArrays & Hashing

給定字串 text,回傳能用其中的字元拼出多少個 “balloon”。每個字元只能使用一次。

Example:

Input: text = “loonbalxballpoon” Output: 2

Intuition

TIP

核心思路:統計 text 中 b, a, l, o, n 各出現幾次,“balloon” 中 l 和 o 各需要 2 個,取最小值即為答案。

Approaches

1. Full Character Count — O(n) / O(1)
  • Idea: 統計所有 26 個字母出現次數,再對 “balloon” 每個字母做除法取最小值
  • Time: O(n) - 遍歷字串一次
  • Space: O(1) - 固定大小陣列
class Solution {
    fun maxNumberOfBalloons(text: String): Int {
        val count = IntArray(26)
        for (c in text) {
            count[c - 'a']++
        }
        var result = count['b' - 'a']
        result = minOf(result, count['a' - 'a'])
        result = minOf(result, count['l' - 'a'] / 2)
        result = minOf(result, count['o' - 'a'] / 2)
        result = minOf(result, count['n' - 'a'])
        return result
    }
}
⭐ 2. Count 'balloon' Chars, Min Multiple — O(n) / O(1)
  • Idea: 同時統計 text 和 “balloon” 的字元頻率,對每個必要字元計算可用倍數,取最小值
  • Time: O(n)
  • Space: O(1)
class Solution {
    fun maxNumberOfBalloons(text: String): Int {
        val countText = HashMap<Char, Int>()
        for (c in text) {
            countText[c] = (countText[c] ?: 0) + 1
        }
        val countBalloon = HashMap<Char, Int>()
        for (c in "balloon") {
            countBalloon[c] = (countBalloon[c] ?: 0) + 1
        }
        var result = Int.MAX_VALUE
        for ((c, need) in countBalloon) {
            result = minOf(result, (countText[c] ?: 0) / need)
        }
        return result
    }
}

🔑 Takeaways