LeetCode 929. Unique Email Addresses

929. Unique Email Addresses

Every email consists of a local name and a domain name, separated by the @ sign.python

For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.markdown

Besides lowercase letters, these emails may contain '.'s or '+'s.app

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.)dom

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.)ide

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?this

Example 1:code

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:leetcode

  • 1 <= emails[i].length <= 100
  • 1 <= emails.length <= 100
  • Each emails[i] contains exactly one '@' character.

题目描述:大概是给你个邮箱的列表,给了一个 local name 的命名规则,问若是同时向这些邮箱中发送邮件,有多少不一样邮箱可以实际收到这些邮件。rem

题目分析:挺水的一道题,首先,邮箱是由local name + @ + domain name 组成。咱们从题意能够知道给出 local name 的两条命名规则:

  • 遇到 . 直接无视。例如 alice.z@leetcode.comalicez@leetcode.com 是等价的关系
  • 遇到 + ,忽略 + 后面的内容。例如 m.y+name@email.commy@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();
    }
};
相关文章
相关标签/搜索