[LeetCode] 929. Unique Email Addresses
Easy
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. - All local and domain names are non-empty.
- Local names do not start with a
'+'
character.
题目大意:邮箱地址以@区分local和domain,@后的为domain,@前的为local。local中如果有'.',则将其忽略,如果有'+',则将其以及其后的部分忽略,剩下的部分为真正的local地址。
输入一组邮箱地址,得出共有多少种不同的邮箱地址。
看到local部分的规定,首先就要对每个输入的邮箱地址进行处理,去掉local中的'.'和第一个'+'~'@'之间的字段。然后用map记录邮箱地址出现情况。
值得注意的是,要删除的'+'~'@'之间的部分中可能还包含'+',所以要对是否为第一次出现'+'进行标记,另外不要将domain中的'.',因为domain中的'.'是有效的。
代码如下:
class Solution { public: int numUniqueEmails(vector<string>& emails) { int res = 0; map <string, int> emailNum; for (string email : emails) { int plusFlag = 0,flag = 0; for (int i=0; i < email.size() ; ++i) { if (email[i] == '.') { email.erase(i,1); } else if (email[i] == '+' && flag == 0) { plusFlag = i; flag = 1; } else if (email[i] == '@') { if (plusFlag != 0) { email = email.erase(plusFlag, i - plusFlag); } break; } } emailNum[email] += 1; } res = emailNum.size(); return res; } };
寻找'.','+','@'时也可以使用string的find函数,但是注意随着字符串的部分字符的不断剔除,字符串中指定字符的位置会不断改变。
代码的运行时间略有提升,但效果并不显著。使用find函数只是让代码看起来逻辑更清楚。
代码如下:
class Solution { public: int numUniqueEmails(vector<string>& emails) { int res = 0; map <string, int> emailNum; for (string email : emails) { if (email.find('+') != -1) { int i = email.find('+'); int j = email.find('@'); email.erase(i, j - i); } while (email.find('.') != -1 && email.find('.') < email.find('@')) { email.erase(email.find('.'), 1); } emailNum[email] += 1; } res = emailNum.size(); return res; } };