LeetCode 929 Unique Email Addresses--python一行解法,Java解法


LeetCode题解专栏:LeetCode题解
我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。


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.

谷歌翻译的题目:
每封电子邮件都包含本地名称和域名,以@符号分隔。

例如,在[email protected], alice是当地的名,leetcode.com是域名。

除了小写字母,这些电子邮件可能包含’.‘s或’+'s。

如果’.'在电子邮件地址的本地名称部分中的某些字符之间添加句点(),则在那里发送的邮件将转发到本地名称中没有点的相同地址。例如,"[email protected]"并且"[email protected]"转发到相同的电子邮件地址。(请注意,此规则不适用于域名。)

如果’+'在本地名称中添加加号(),则将忽略第一个加号后面的所有内容 。这允许过滤某些电子邮件,例如 [email protected] 将被转发到 [email protected]。(同样,此规则不适用于域名。)

可以同时使用这两个规则。

根据列表emails,我们会向列表中的每个地址发送一封电子邮件。有多少不同的地址实际接收邮件?


python一行解法:

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        return len(set(x.split('@')[0].split('+')[0].replace('.','')+x.split('@')[1] for x in emails))

java常规解法:
注意:参考答案的Java解法是错误的

class Solution {
    public int numUniqueEmails(String[] emails) {
       Set<String> normalized = new HashSet<>(); // used to save simplified email address, cost O(n) sapce.
        for (String email : emails) {
            String[] parts = email.split("@"); // split into local and domain parts.
            String[] local = parts[0].split("\\+"); // split local by '+'.
            normalized.add(local[0].replace(".", "") + "@" + parts[1]); // remove all '.', and concatenate '@' and domain.        
        }
        return normalized.size();
        
    }
}

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/88702781
今日推荐