05 August 2008
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in
, 1
alice@leetcode.com
is the local name, and 1
alice
is the domain name.1
leetcode.com
Besides lowercase letters, these emails may contain
s or 1
'.'
s.1
'+'
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, 1
'.'
and 1
"alice.z@leetcode.com"
forward to the same email address. (Note that this rule does not apply for domain names.)1
"alicez@leetcode.com"
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 1
'+'
will be forwarded to 1
m.y+name@email.com
. (Again, this rule does not apply for domain names.)1
my@email.com
It is possible to use both of these rules at the same time.
Given a list of
, we send one email to each address in the list. How many different addresses actually receive mails?1
emails
Example 1:
1
2
3
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
1 <= emails[i].length <= 100
1
1 <= emails.length <= 100
1
emails[i]
contains exactly one 1
'@'
character.1
'+'
character.根据题意,”.”可以忽略,”+”在名字的位置后面的忽略,domain name照常比较。
直接的思路,用hashset除重。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int numUniqueEmails(String[] emails) {
HashSet<String> set = new HashSet<>();
int count = 0;
for (String email : emails) {
String[] arr = email.split("@", 2); // @只出现一次
StringBuilder sb = new StringBuilder();
int index = 0;
while (index < arr[0].length() && arr[0].charAt(index) != '+') {
if (arr[0].charAt(index) != '.') {
sb.append(arr[0].charAt(index));
}
index++;
}
sb.append("@");
sb.append(arr[1]);
if (set.add(sb.toString())) {
count++;
}
}
return count;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int numUniqueEmails(String[] emails) {
if (emails == null || emails.length == 0) {
return 0;
}
Set<String> result = new HashSet<>();
for (String email : emails) {
StringBuilder sb = new StringBuilder();
String[] splitted = email.split("\\@");
char[] letters = splitted[0].toCharArray();
for (char letter : letters) {
if (letter != '+') {
if (Character.isLetterOrDigit(letter)) {
sb.append(letter);
} else if (letter == '.') {
continue;
}
} else {
break;
}
}
if (!sb.toString().isEmpty()) {
sb.append(splitted[1]);
result.add(sb.toString());
}
}
return result.size();
}
}