very 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
emails[i]
contains exactly one '@'
character.'+'
character.题目分析:给定一个email address数组, 输出有多少个不同的email adress,Email Adress 以“@”为分割点
①在"@"左边,假如出现".",则默认忽略,比如[email protected]其实等价于[email protected];假如出现"+", 则"+"到"@"之间的内容则全部忽略,比如[email protected]+n其实等价于[email protected]+n;
②在"@"右边,假如出现"."和"+",就不会有什么变化。
利用Set集合,里边不包含重复元素的特性进行去重:
import java.util.HashSet;
import java.util.Set;
class Solution {
public static int numUniqueEmails(String[] emails) {
Set set = new HashSet(); // 利用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 = {"[email protected]", "[email protected]"};
System.out.println(new Solution().numUniqueEmails(emails));
}
}