very 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 <= 1001 <= emails.length <= 100- Each
emails[i]contains exactly one'@'character. - All local and domain names are non-empty.
- Local names do not start with a
'+'character.
题目分析:给定一个email address数组, 输出有多少个不同的email adress,Email Adress 以“@”为分割点
①在"@"左边,假如出现".",则默认忽略,比如c.o.d.e@qq.com.cn其实等价于code@qq.com.cn;假如出现"+", 则"+"到"@"之间的内容则全部忽略,比如c.o.d.e+love@qq.com.c+n其实等价于code@qq.com.c+n;
②在"@"右边,假如出现"."和"+",就不会有什么变化。
利用Set集合,里边不包含重复元素的特性进行去重:
import java.util.HashSet;
import java.util.Set;
class Solution {
public static int numUniqueEmails(String[] emails) {
Set<String> set = new HashSet<String>(); // 利用set元素
for (String e : emails) {
int atIndex = e.indexOf("@"); // 找到@所在的索引
StringBuffer sb = new StringBuffer();
for (int i = 0; i < atIndex; i++) { // 只需要循环@前边的字符
if (e.charAt(i) == '.') continue; // 遇到“.”就直接进行下一轮循环
if (e.charAt(i) == '+') { // 遇到“+”则退出循环
break;
} else {
sb.append(e.charAt(i));
}
}
set.add(sb.append("@").append(e.substring(atIndex)).toString()); // 拼接“@”和“@”后边的字符,然后添加进Set集合中。
}
return set.size();
}
public static void main(String[] args) {
String[] emails = {"test.email+alex@leetcode.com", "test.email@leetcode.com"};
System.out.println(new Solution().numUniqueEmails(emails));
}
}
本文探讨了如何处理和标准化电子邮件地址,特别是针对那些包含特殊字符如'.'和'+'的情况。通过实例演示,我们了解到在'@'符号左侧的部分,'.'会被忽略,而'+'之后的内容将被省略,这有助于减少邮件系统的复杂性并提高过滤效率。文章最后提供了一个Java代码示例,展示了如何使用HashSet来去除重复的电子邮件地址。
549

被折叠的 条评论
为什么被折叠?



