LeetCode 929. Unique Email Addresses
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.
Besides lowercase letters, these emails may contain '.'
s or '+'
s.
If you add periods ('.'
"[email protected]"
and "[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]
. (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: ["[email protected]","[email protected]","[email protected]"]
Output: 2
Explanation: "[email protected]" and "[email protected]" 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
的兩條命名規則:
- 遇到
.
直接無視。例如[email protected]
和[email protected]
是等價的關係 - 遇到
+
,忽略+
後面的內容。例如[email protected]
和[email protected]
是等價的關係
我們考慮用集合進行去重操作,同一郵箱收到多條郵件只能算做一次。列舉郵箱列表中的郵箱地址,根據 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();
}
};