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

LeetCode 804: Unique Morse Code Words

·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-07

  • 提交紀錄:Accepted(一次通過)

解題思路
#

照表把每個字母換成摩斯碼、接成一個字串,放進集合,答案是集合的大小(Hash Table)。字母 c 的編碼是 table[ord(c) - ord("a")]。

我的解法
#

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        table = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
                 "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
                 "..-", "...-", ".--", "-..-", "-.--", "--.."]
        return len({"".join(table[ord(c) - ord("a")] for c in w) for w in words})

複雜度
#

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

要特別避免的錯誤
#

  • 不同單字可能有相同的摩斯碼,這正是題目要數的。

面試口說整理
#

我把每個單字照表轉成摩斯碼字串,放進集合,集合的大小就是答案。時間是總字元數。

相關文章

LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
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 594: Longest Harmonious Subsequence
·1 分鐘
LeetCode Easy Array Hash-Table Sliding-Window Sorting
LeetCode 594 解題筆記:子序列不用連續,所以只要計數,每個 x 看 x 和 x + 1 的次數加起來
LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值