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 <= emails[i].length <= 100
1 <= emails.length <= 100
- Each
emails[i]
contains exactly one'@'
character.
题目描述:大概是给你个邮箱的列表,给了一个 local name
的命名规则,问如果同时向这些邮箱中发送邮件,有多少不同邮箱能够实际收到这些邮件。
题目分析:挺水的一道题,首先,邮箱是由local name
+ @
+ domain name
组成。我们从题意可以知道给出 local name
的两条命名规则:
- 遇到
.
直接无视。例如alice.z@leetcode.com
和alicez@leetcode.com
是等价的关系 - 遇到
+
,忽略+
后面的内容。例如m.y+name@email.com
和my@email.com
是等价的关系
我们考虑用集合进行去重操作,同一邮箱收到多条邮件只能算做一次。枚举邮箱列表中的邮箱地址,根据 local name
的命名规则,通过 split
函数分割,将真实邮箱存入集合中,然后计算出的集合中的元素个数即为我们所求的邮箱数。
python
代码:
class Solution(object):
def numUniqueEmails(self, emails):
"""
:type emails: List[str]
:rtype: int
"""
real_email = set()
for i in range(len(emails)):
x = emails[i]
s = str(x.split("+")[0].replace('.','') + '@' + x.split("@")[1])
real_email.add(s)
return len(real_email)
C++
代码:
class Solution {
public:
int numUniqueEmails(vector<string>& emails) {
set<string> x;
for(int i = 0; i < emails.size(); i++){
if(emails[i].find('.') != string::npos){
emails[i].erase(remove(emails[i].begin(), find(emails[i].begin(), emails[i].end(),'@'), '.'), find(emails[i].begin(), emails[i].end(), '@'));
}
if(emails[i].find('+') != string::npos){
emails[i].erase(find(emails[i].begin(), find(emails[i].begin(), emails[i].end(), '@'), '+'), find(emails[i].begin(), emails[i].end(), '@'));
}
x.insert(emails[i]);
}
return x.size();
}
};