[LeetCode] 929. Unique Email Addresses
Description
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?
Example 1:
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 <= emails[i].length <= 100
- 1 <= emails.length <= 100
- Each emails[i] contains exactly one '@' character.
Analyse
简单题,邮箱地址@
前面的部分中的.
直接省略,+
后面的部分也省略, @
后面的域名部分不作变换,剩下的就是真正的邮箱地址
test.email+alex@leetcode.com
-> testemail@leetcode.com
把变换后的邮箱地址存到set里去就能拿到不同的邮箱地址数了
Code
第一个版本的代码,先把邮箱地址按@
分割成两部分,前面是localName,后面是domain,作完变换后insert到unordered_set
中,输出长度
48ms faster than 4.89%
int numUniqueEmails(vector<string>& emails)
{
unordered_set<string> ss;
string localName;
string domain;
string tmp = "";
for(int i = 0; i < emails.size(); i++)
{
tmp = emails[i];
size_t at_pos = tmp.find('@');
if (at_pos != string::npos)
{
localName = tmp.substr(0, at_pos);
domain = tmp.substr(at_pos + 1, emails[i].size());
localName.erase(std::remove(localName.begin(), localName.end(), '.'), localName.end()); //去除localName中所有`.`
size_t plus_pos = localName.find('+');
localName = localName.substr(0, plus_pos);
cout << localName + domain << endl;
ss.insert(localName + domain);
}
else
{
continue;
}
}
return ss.size();
}
上面那个版本的结果太差了,我猜测是erase
那段花的时间太长了,自己用for循环实现了一遍,结果结果并没有发生变化,还是48ms,直到我删除了那行cout
20ms faster than 96.49%
int numUniqueEmails(vector<string>& emails) {
unordered_set<string> ss;
string email = "";
for(int i = 0; i < emails.size(); i++)
{
email = emails[i];
string address = "";
size_t at_pos = email.find('@');
string domain = email.substr(at_pos + 1, email.size());
string localName = email.substr(0, at_pos);
for(int j = 0; j < localName.size(); j++)
{
if (localName[j] == '+')
{
break;
}
if (localName[j] == '.')
{
continue;
}
address += localName[j];
}
ss.insert(address + domain);
}
return ss.size();
}