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

LeetCode 1160: Find Words That Can Be Formed by Characters

·1 分鐘· ·
LeetCode Easy Array 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

  • 提交紀錄:Accepted ×3

解題思路
#

先數一次 chars(Hash Table 模板一),每個單字也數一次,Counter(w) - C 是空的代表每個字元都夠用(跟 LC 383 一樣),就把長度加進答案。

我的解法
#

class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        have = Counter(chars)
        return sum(len(w) for w in words if not (Counter(w) - have))

複雜度
#

時間 O(總字元數),空間 O(k)。

要特別避免的錯誤
#

  • chars 的次數在迴圈外算一次就好,每個單字可以重複使用全部的 chars。

面試口說整理
#

我先數 chars 每個字元有幾個,再對每個單字檢查它需要的次數都沒有超過,可以組成的就加上長度。時間是所有單字的總長度。

相關文章

LeetCode 819: Most Common Word
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 解題筆記:標點換成空白、全部轉小寫再切單字,計數後找出不在 banned 裡的最多的那個
LeetCode 804: Unique Morse Code Words
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 804 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 1128: Number of Equivalent Domino Pairs
·1 分鐘
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 解題筆記:把每張骨牌正規化成 (小, 大) 當 key 計數,每個 key 有 c 張就有 c(c - 1) / 2 對
LeetCode 1189: Maximum Number of Balloons
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 1189 解題筆記:每個字母可以組幾個 balloon 是 次數 // 需要數,l 和 o 需要兩個,取最小值
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開