↓快轉到主要內容
  1. LeetCode/

LeetCode 1189: Maximum Number of Balloons

·1 分鐘· ·
LeetCode Easy Hash-Table String Counting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-10-18

  • 提交紀錄:Runtime Error → Wrong Answer ×4 → Accepted → Runtime Error ×3 → Wrong Answer → Accepted ×2

解題思路
#

balloon 需要 b, a, n 各一個、l, o 各兩個。數 text 的字元(Hash Table 模板一),每個字母能組出 cnt[c] // need[c] 個,答案是這五個值的最小值。

我的嘗試
#

這題提交了 12 次:

  • 第一版把字母 s 本身指定給 res,而不是次數 C[s],TypeError。
  • 接下來四版外層先用 C[s] < res 篩選,比的是原始次數而不是除以 2 之後的,l 只有一個時 1 < 1 不成立,就被跳過了:"nolab" 答案 0,回傳 1。
  • 改成 walrus 之後先是語法錯誤,然後寫成 (new := C[s] // 2 < res),new 拿到的是比較結果 True:"ban" 回傳 True。括號移到 (new := C[s] // 2) < res 才 AC。

正確解法
#

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        cnt = Counter(text)
        need = Counter("balloon")
        return min(cnt[c] // need[c] for c in need)

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 先把次數除以需要的數量,再取最小值;不要先用原始次數篩選。
  • walrus 要加括號:(new := x // 2) < res,不然 new 拿到的是比較的結果。

面試口說整理
#

我數 text 的字元,每個字母除以 balloon 裡需要的數量,l 和 o 要兩個,五個值取最小就是答案。時間 O(n)。

相關文章

LeetCode 884: Uncommon Words from Two Sentences
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 884 解題筆記:把兩個句子合起來數每個單字的次數,只出現一次的就是答案
LeetCode 819: Most Common Word
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 解題筆記:標點換成空白、全部轉小寫再切單字,計數後找出不在 banned 裡的最多的那個
LeetCode 383: Ransom Note
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 383 解題筆記:ransomNote 每個字元的需求數量都不能超過 magazine 的數量;Counter 相減為空就成立
LeetCode 387: First Unique Character in a String
·1 分鐘
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 解題筆記:先計數,再從左到右找第一個次數是 1 的字元
LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 1128: Number of Equivalent Domino Pairs
·1 分鐘
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 解題筆記:把每張骨牌正規化成 (小, 大) 當 key 計數,每個 key 有 c 張就有 c(c - 1) / 2 對