https://leetcode.com/problems/unique-email-addresses/
https://leetcode.com/problems/unique-email-addresses/discuss/186798/Java-7-liner-with-comment.
https://leetcode.com/problems/unique-email-addresses/discuss/186645/Java-Clean-O(n*maxStringLen)-with-and-without-split()
Every 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?
Approach 1: Canonical Form
For each email address, convert it to the canonical address that actually receives the mail. This involves a few steps:
- Separate the email address into a
local
part and therest
of the address. - If the
local
part has a'+'
character, remove it and everything beyond it from thelocal
part. - Remove all the zeros from the
local
part. - The canonical address is
local + rest
.
After, we can count the number of unique canonical addresses with a
Set
structure.
public int numUniqueEmails(String[] emails) {
Set<String> seen = new HashSet();
for (String email : emails) {
int i = email.indexOf('@');
String local = email.substring(0, i);
String rest = email.substring(i);
if (local.contains("+")) {
local = local.substring(0, local.indexOf('+'));
}
local = local.replaceAll(".", "");
seen.add(local + rest);
}
return seen.size();
}
public int numUniqueEmails(String[] emails) {
Set<String> set = new HashSet<>();
for (String email : emails){
String[]parts = email.split("@");
String local = parseLocal(parts[0]);
String domain = parts[1];
set.add(local + '@' + domain);
}
return set.size();
}
String parseLocal(String local){
StringBuilder sb = new StringBuilder();
for (char c : local.toCharArray()){
if (c != '.'){//Skip the period characters
if (c == '+') return sb.toString(); //Ignore everything else
sb.append(c); //Not a period and not a + character
}
}
return sb.toString();
}