Leetcode 929. Unique Email Addresses
You are given a list of emails. Each email contains 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, it will not change the email address. For example, alice.z@leetcode.com
and alicez@leetcode.com
are the same email address.
If you add a plus ('+'
) in the local name, it will ignore everything after the first plus sign. This allows certain emails to be filtered. For example, m.y+n.a.m.e+filter@leetcode.com
will be sent to my@leetcode.com
.
This means that both alice.z@leetcode.com
and alicez@leetcode.com
will be considered the same, as will m.y+n.a.m.e+filter@leetcode.com
and my@leetcode.com
.
Your task is to count the number of unique email addresses from a given list of emails.
Set
to hold the processed email addresses.'.'
).import java.util.HashSet;
import java.util.Set;
public class UniqueEmailAddresses {
public int numUniqueEmails(String[] emails) {
Set<String> uniqueEmails = new HashSet<>();
for (String email : emails) {
String[] parts = email.split("@");
String local = parts[0];
String domain = parts[1];
// Ignore everything after '+' in the local part
if (local.contains("+")) {
local = local.substring(0, local.indexOf('+'));
}
// Remove all periods from the local part
local = local.replace(".", "");
// Combine the cleaned local part with the domain
String cleanedEmail = local + "@" + domain;
// Add the cleaned email to the set
uniqueEmails.add(cleanedEmail);
}
// The size of the set is the number of unique email addresses
return uniqueEmails.size();
}
public static void main(String[] args) {
UniqueEmailAddresses solution = new UniqueEmailAddresses();
String[] emails = {
"test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com"
};
System.out.println(solution.numUniqueEmails(emails)); // Output: 2
}
}
n
is the number of emails and m
is the average length of an email. This is because each email is processed individually with a loop through split
, replace
, and other string operations.This solution ensures that we efficiently filter and count the number of unique email addresses by leveraging string manipulation and a set to enforce uniqueness.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?