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

LeetCode 819: Most Common Word

·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-09-14

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

解題思路
#

先正規化:把不是字母的字元換成空白(不是刪掉,不然 a,b 會黏成 ab),再全部轉小寫、split()(String 模板四)。banned 放進集合,計數時跳過(Hash Table 模板一),最後取次數最多的。

我的嘗試
#

這題提交了 8 次,每次錯在正規化的一個細節:

  • 第一版用 paragraph[:-1] 想去掉結尾的標點,但段落不一定有標點,"a" 被切成空字串。
  • 第二版直接刪掉標點:"a'a" 變成 "aa",答案是 "a"。
  • 改成把標點換成空白後,有一版變數名稱打錯(NameError),另外兩版忘了轉小寫:"Bob" 回傳 "Bob",答案 "bob"。

正確解法
#

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        words = "".join(c.lower() if c.isalpha() else " " for c in paragraph).split()
        ban = set(banned)
        cnt = Counter(w for w in words if w not in ban)
        return cnt.most_common(1)[0][0]

複雜度
#

時間 O(n + b),空間 O(n + b)。

要特別避免的錯誤
#

  • 標點要換成空白,不能直接刪掉。
  • 大小寫視為相同,要轉小寫。
  • 不要切掉最後一個字元:段落不一定以標點結尾。

面試口說整理
#

我先把非字母換成空白、轉小寫再切成單字,banned 放進集合,計數時跳過,最後回傳次數最多的單字。時間 O(n + b)。

相關文章

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 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 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 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留