Leetcode 929. Unique Email Addresses
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 also contain '.'
or '+'
.
'.'
) to 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 address.'+'
) to the local name, it will ignore everything after the plus sign. This allows certain email filtering. For example, "alice+leetcode@leetcode.com"
and "alice@leetcode.com"
forward to the same email address.Given a list of email addresses, we need to determine the number of unique addresses.
#include <iostream>
#include <unordered_set>
#include <vector>
class Solution {
public:
int numUniqueEmails(std::vector<std::string>& emails) {
std::unordered_set<std::string> uniqueEmails;
for (const std::string& email : emails) {
std::string localName;
std::string domainName;
bool atSymbol = false;
bool ignoreRest = false;
for (char c : email) {
if (c == '@') {
atSymbol = true;
}
if (atSymbol) {
domainName += c;
} else {
if (c == '+') {
ignoreRest = true;
}
if (!ignoreRest && c != '.') {
localName += c;
}
}
}
uniqueEmails.insert(localName + domainName);
}
return uniqueEmails.size();
}
};
int main() {
Solution sol;
std::vector<std::string> emails = {
"test.email+alex@leetcode.com",
"test.e.mail+bob.cathy@leetcode.com",
"testemail+david@lee.tcode.com"
};
std::cout << sol.numUniqueEmails(emails) << std::endl; // Output should be 2
return 0;
}
uniqueEmails
) to store the unique email addresses.'+'
.'.'
characters in the local name.uniqueEmails
set.uniqueEmails
set represents the number of unique email addresses.The overall time complexity is O(n*m), where n
is the number of emails in the list, and m
is the average length of an email address. This results from processing each character in each email once. The unordered_set
operations (insert and lookup) are average O(1), making the solution efficient.
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?