Unique Email Addresses LeetCode Solution
Question
Every valid email consists of a local name and a domain name, separated by the '@'
sign. Besides lowercase letters, the email may contain one or more '.'
or '+'
.
- For example, in
"alice@leetcode.com"
, "alice"
is the local name, and "leetcode.com"
is the domain name.
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. Note that this rule does not apply to domain names.
- For example,
"alice.z@leetcode.com"
and "alicez@leetcode.com"
forward to the same email address.
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. Note that this rule does not apply to domain names.
- For example,
"m.y+name@email.com"
will be forwarded to "my@email.com"
.
It is possible to use both of these rules at the same time.
Given an array of strings emails
where we send one email to each email[i]
, return the number of different addresses that actually receive mails.
Example 1
Input: emails = ["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.
Example 2
Input: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]
Output: 3
Explanation
This question is easy but looks a bit complicated at first sight. The problem can be solved using hashmap, set, unordered set. Lets see the approach now. Dividing the each email into two parts
Local name - Building it by traversing the each character in every email and adding it into a tempMail string
i) if local name contains "." continue making the local name in the tempMail string.
ii) if local name contains "+" everything after would be ignored thus break the loop.
iii) if while traversing "@" is encountered that means we have completed the traversal for local name, break the loop.
Domain Name - No filters are given for this, So just adding it as it after we have made our local string.
An unordered_set of strings could be used to store the every new tempMail. So that even though we will be pushing the multiple copy entries, its size would only give the size of unique entries. In this piece of code, I took lots of times to recall regex, and it is the most unreadable part, so let me explain:
/\+.*$|\./g
+ is a special char, so adds \.
.* means any character after +.
$, in regex, it represents the end of string.
| equals to or.
. is also a special char, so adds \.
In the end of regex, g, global search, means finding all matches in input and replace them.
In sum, replace the substring that after sign + or the char . with empty string.
That's all you need to know about. Hope you understood the explanation. I recommend to try the problem by yourself then if you are stuck you can visit the solution given below in Java, C++, Python.
Program Code
Java
class Solution {
public int numUniqueEmails(String[] emails) {
HashSet<String> set = new HashSet<>();
for(String s : emails){
StringBuilder sb = new StringBuilder();
int at = s.indexOf("@");
for(int i=0;i<at;i++){
char ch = s.charAt(i);
if(ch == '+') break;
if(ch!='.') sb.append(ch);
}
sb.append(s.substring(at));
set.add(sb.toString());
}
return set.size();
}
}
C++
int numUniqueEmails(vector<string>& emails) {
set<string>s;
for(auto i:emails){
string d=i;
string temp;
int x=0;
for(x;d[x]!='@';x++){
if(d[x]=='+'){
break;
}
if(d[x]!='.'){
temp.push_back(d[x]);
}
}
while(d[x]!='@'){
x++;
}
for(x;x<d.size();x++){
temp.push_back(d[x]);
}
cout<<temp<<endl;
s.insert(temp);
}
return s.size();
}
Python
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
email_set = set()
for email in emails:
name, domain = email.split('@')
name = name.replace('.', '')
if '+' in name:
name = name[:name.index('+')]
email_set.add(name + '@' + domain)
return len(email_set)
Suggested Links
More information about LeetCode Daily Challenge
More Information About LeetCode Daily Challenge
LeetCode is a great coding platform which provides daily problems to solve and maintain a streak of coding. This platform helps in improvement of coding skills and attempting the daily challenge makes our practice of coding regular. With its bunch of questions available it is one of the best coding platforms where you can have self improvement. LeetCode also holds weekly and biweekly contests which is a great place to implement you knowledge and coding skills which you learnt through out the week by performing the daily challenge. It also provides badges if a coder solves all the daily problems of a month. For some lucky winners T-shirts are also given and that too for free. If you get the pro version you can get more from LeetCode like questions that are asked in interviews, detailed explanation of each chapter and each concept and much more. LeetCode challenges participants with a problem from our carefully curated collection of interview problems every 24 hours.
All users with all levels of coding background are welcome to join!
@PREMIUM USERS will have an extra carefully curated premium challenge weekly and earn extra LeetCoin rewards. The premium challenge will be available together with the first October challenge of the week and closed together with the November challenge of the week.
Starting from 2021, users who completed all Daily LeetCoding Challenge non-premium problems for the month (with or without using Time Travel Tickets) will win a badge to recognize their consistency! Your badges will be displayed on your profile page. Completing each non-premium daily challenge. (+10 LeetCoins)
Completing 25 to 30 non-premium daily challenges without using Time Travel Ticket will be eligible for an additional 25 LeetCoins. (Total = 275 to 325 LeetCoins)
Completing all 31 non-premium daily challenges without using Time Travel Ticket will be eligible for an additional 50 LeetCoins, plus a chance to win a secret prize ( Total = 385 LeetCoins + *Lucky Draw)!
Lucky Draw: Those who complete all 31 non-premium daily challenges will be automatically entered into a Lucky Draw, where LeetCode staff will randomly select 3 lucky participants to each receive one LeetCode Polo Shirt on top of their rewards! Do you have experience trying to keep a streak but failed because you missed one of the challenges?
Hoping you can travel back to the missed deadline to complete the challenge but that's not possible......or is it?
With the new Time Travel Ticket , it's possible! In order to time travel, you will need to redeem a Time Travel Ticket with your LeetCoins. You can redeem up to 3 tickets per month and the tickets are only usable through the end of the month in which they are redeemed but you can use the tickets to make up any invalid or late submission of the current year. To join, just start solving the daily problem on the calendar of the problem page. You can also find the daily problem listed on the top of the problem page. No registration is required. The daily problem will be updated on every 12 a.m. Coordinated Universal Time (UTC) and you will have 24 hours to solve that challenge. Thar's all you needed to know about Daily LeetCode Challenge.
Comments
Post a Comment