LeetCode 929 Unique Email Addresses 解題報告
題目要求
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in [email protected]
, alice
is the local name, and leetcode.com
is the domain name.
If you add periods (‘.‘
) between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "[email protected]"
"[email protected]"
forward to the same email address. (Note that this rule does not apply for domain names.)
If you add a plus (‘+‘
) in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example [email protected]
will be forwarded to [email protected]
It is possible to use both of these rules at the same time.
Given a list of emails
, we send one email to each address in the list. How many different addresses actually receive mails?
Input: ["[email protected]","[email protected]","[email protected]"]
?Output: 2
?Explanation: "[email protected]" and "[email protected]" actually receive mails
1 <= emails[i].length <= 100
1 <= emails.length <= 100
?
Each emails[i]
contains exactly one ‘@‘
character.
題目分析及思路
題目要求得到一組郵件地址中不重復的地址的個數,規則是用戶名部分有‘.’,則和無‘.’的用戶名一樣;用戶名部分有‘+’,則忽略第一個‘+’後面的部分。兩個規則可以同時生效,但對域名部分不起作用。所以先對郵件進行拆分,分為用戶名部分和域名部分;之後先找到‘+’,去掉‘+’及後面部分,再去掉‘.’。最後再和‘@’及域名連接。因為要去重,所以使用一個set保存所有不重復的結果。
python代碼?
class Solution:
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
emailsset = set()
for e in emails:
local,domain = e.split("@")
local = local.split("+")[0].replace(".","")
emailsset.add(local+"@"+domain)
return len(emailsset)
LeetCode 929 Unique Email Addresses 解題報告