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

LeetCode 929: Unique Email Addresses

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

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

解題思路
#

把每個信箱正規化後放進集合(Hash Table 模板五):用 @ 切成 local 和 domain,local 先砍掉第一個 + 之後的內容、再刪掉所有 .;domain 不動。接回去時要把 @ 加回來,不然不同的信箱可能接成同一個字串。

我的嘗試
#

  • 第一版 replace 拼錯(AttributeError)。
  • 接下來兩版用 "".join(email) 接回去,@ 不見了:["a@bx.com", "ab@x.com"] 都變成 "abx.com",答案 2,回傳 1。
  • 再下一版寫成 emails[0] + '@' + emails[1],email 和 emails 搞混了,只有一個信箱時 IndexError。

正確解法
#

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        seen = set()
        for e in emails:
            local, domain = e.split("@")
            local = local.split("+")[0].replace(".", "")
            seen.add(local + "@" + domain)
        return len(seen)

複雜度
#

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

要特別避免的錯誤
#

  • 規則只套用在 local 的部分,domain 的 . 要保留。
  • 接回去時要保留 @:"a@bx.com" 和 "ab@x.com" 是不同的信箱。

面試口說整理
#

我用 @ 把信箱切成兩半,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 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留