日期:2026年6月22日
LeetCode 題目連結:1189. Maximum Number of Balloons
解題想法
簡單題,題目給定字串 text,要計算用 text 之中的字母可以組成幾個 balloon,每個字母最多只能使用一次。只要先計算 text 之中,字母 a, b, l, o, n 分別有幾個,計算 b, a, n 的數量及 l, o 的數量除以 2,答案是這 5 個數值中的最小值。計算字母數量時可以用表格計數,也可以使用字典計數。
Python 程式碼
dict,建立 dict 物件 cnt 時設定好 key 值,只記錄 a, b, l, o, n 的數量。Runtime: 3 ms, beats 61.87%. Memory: 19.24 MB, beats 75.19%.
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
# 用字典記錄 balon 的字母數量
cnt = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}
for c in text:
if c in cnt:
cnt[c] += 1
# 找 ban 字母數量最小值,lo 字母數量 / 2 最小值
ans = 100000
for c in "ban":
ans = min(ans, cnt[c])
for c in "lo":
ans = min(ans, cnt[c] // 2)
return ans
dict,建立 dict 物件 cnt 時設定好 26 個字母的 key 值,記錄所有字母的數量。Runtime: 3 ms, beats 61.87%. Memory: 19.10 MB, beats 99.41%.
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
# 用字典記錄 balon 的字母數量
cnt = {chr(ord('a') + i): 0 for i in range(26)}
for c in text:
cnt[c] += 1
# 找 ban 字母數量最小值,lo 字母數量 / 2 最小值
ans = 100000
for c in "ban":
ans = min(ans, cnt[c])
for c in "lo":
ans = min(ans, cnt[c] // 2)
return ans