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

LeetCode 1002: Find Common Characters

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

基本資料
#

難易度: easy 第一次嘗試:2022-09-27

  • 提交紀錄:Runtime Error → Accepted ×3

解題思路
#

答案中每個字元的次數,是它在每個單字中出現次數的最小值(Hash Table 模板一)。Python 的 Counter & Counter 就是逐字元取最小值,對所有單字做完後用 elements() 展開。

我的嘗試
#

第一版用 set 跟字串取交集(set & str,TypeError),而且 set 本來就會丟掉重複的次數,["bb"] 應該回傳兩個 b。之後改用 Counter & 才 AC。

正確解法
#

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        common = Counter(words[0])
        for w in words[1:]:
            common &= Counter(w)
        return list(common.elements())

複雜度
#

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

要特別避免的錯誤
#

  • 用 set 會丟掉重複次數:["bb"] 的答案是 ["b", "b"]。
  • set & str 型別不同,會 TypeError。

面試口說整理
#

我對每個單字計數,然後對所有 Counter 取交集,也就是每個字元取最小的次數,最後展開成 list。時間是所有單字的總長度。

相關文章

LeetCode 929: Unique Email Addresses
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 929 解題筆記:用 @ 切開,只處理 local 的部分(+ 之後丟掉、去掉 .),接回 domain 後放進集合
LeetCode 953: Verifying an Alien Dictionary
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 953 解題筆記:把字母對應到外星順序的 index,相鄰兩個單字找第一個不同的字元比較,沒有不同時短的要在前面
LeetCode 819: Most Common Word
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 解題筆記:標點換成空白、全部轉小寫再切單字,計數後找出不在 banned 裡的最多的那個
LeetCode 748: Shortest Completing Word
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 748 解題筆記:車牌只看字母並轉小寫計數,找出每個字母次數都夠的最短單字,同長度取最前面的
LeetCode 599: Minimum Index Sum of Two Lists
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 599 解題筆記:把 list1 的字串對應到 index,掃 list2 時算兩邊 index 的和,留下和最小的全部字串
LeetCode 804: Unique Morse Code Words
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 804 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種