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 ('.') 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]" 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 的兩條命名規則:

我們考慮用集合進行去重操作,同一郵箱收到多條郵件只能算做一次。枚舉郵箱列表中的郵箱地址,根據 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();
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章