Leetcode 929 Unique Email Addresses

Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain ‘.’s or ‘+’s.

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, “alice.z@leetcode.com“ and “alicez@leetcode.com“ 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 m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)

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?

Example 1:
Input: [“test.email+alex@leetcode.com“,”test.e.mail+bob.cathy@leetcode.com“,”testemail+david@lee.tcode.com“]
Output: 2
Explanation: “testemail@leetcode.com“ and “testemail@lee.tcode.com“ actually receive mails

Note:

  1. 1 <= emails[i].length <= 100
  2. 1 <= emails.length <= 100
  3. Each emails[i] contains exactly one ‘@’ character.

题意分析:
给定一系列的邮件地址,邮件地址可以按照一定的规则进行转换,问经过转换后列表中有多少不同邮件地址。

思路分析:
一道简单的应用题,note中确保了每个邮件地址中只有一个‘@’符号,那么我们用‘@’符号将整个地址分为前半部分和后半部分。

对于后半部分,本身是什么就是什么,我们不做改变
对于前半部分,舍去'+'后后面的所有部分,这也可以使用split()函数做到
然后把前半部分中的'.'替换成''

1
2
3
4
5
6
7
8
9
10
11
# 36ms
class Solution(object):
def numUniqueEmails(self, emails):
d = collections.defaultdict(int)
for ss in emails:
local, domain = ss.split('@')
local = local.split('+')[0]
local = local.replace('.', '')

d[local+domain] += 1
return len(d)