本关任务:在P大的校园网门户中,可以设置除学号外的个性化邮箱名称。
每个邮箱地址都包含一个用户名和一个域名,用@隔开。
例如,在alice@pku.edu.cn
中,alice
是用户名,pku.edu.cn
是域名。
某天,管理门户的老师要求对设置个性化邮箱名称时添加两条过滤规则:
- 用户名中的
.
会被忽略掉,例如alice.z@pku.edu.cn
和alicez@pku.edu.cn
被视为相同邮箱账号; - 用户名中
+
及其后面的字符会被忽略掉,例如m.y+name@pku.edu.cn
和my@pku.edu.cn
被视为相同邮箱账号;
这两种规则可以同时被使用。
现在我们需要维护原来的代码,添加上新的功能,这被称为完善性维护。
请你维护代码,完善numUniqueEmails
函数,使得给出一个邮箱地址列表emails,能返回唯一的邮箱地址数量。
样例:
输入多行:
test.email+alex@pku.edu.cn
test.e.mail+bob.cathy@pku.edu.cn
testemail+david@pku.edu.cn
输出:1
解释:唯一的邮箱地址是 "testemail@pku.edu.cn"。
相关知识
为了完成本关任务,你需要掌握:1.字符串的处理, 2.哈希表的使用方法
C++中的字符串
通过string
关键字声明string对象,常用的函数有size(),substr()
等 具体可以查看C++官方文档。
#include <bits/stdc++.h>
using namespace std;
int main() {
string str = "hello world.";
cout << str.size() << endl;
cout << str << endl;
return 0;
}
输出:
12
hello world.
C++中的哈希表
通过unordered_set<string>
声明一个无序集合容器,只存储不同的元素。可以在O(1)的时间复杂度内插入和删除。
示例如下:
#include <bits/stdc++.h>
using namespace std;
int main() {
unordered_set<string> s;
s.insert("1");
s.insert("1");
s.insert("2");
s.insert("3");
for (auto ss:s) cout << ss << endl;
return 0;
}
输出:
3
1
2
如何求出答案
对于给出的2个新的需求,我们需要对每个字符串按照过滤规则进行处理。
对于唯一性,我们使用哈希表进行记录即可,返回哈希表的大小,即为唯一的邮箱地址。
编程要求
根据提示,在右侧编辑器补充代码,计算并输出正确答案。
测试说明
平台会对你编写的代码进行测试:
开始你的任务吧,祝你成功!
答案
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
int numUniqueEmails(vector<string>& emails) {
//请在此处添加代码,输出唯一的邮箱地址数量
/********** Begin *********/
unordered_set<string> S;
for(auto email : emails)
{
string local, domain;
int k = 0;
while(email[k] != '@') k++;
local = email.substr(0,k);
domain = email.substr(k+1);
string newLocal;
for(auto c : local){
if(c == '+') break;
if(c != '.') newLocal += c;
}
S.insert(newLocal + '@' + domain);
}
return S.size();
/********** End **********/
}
int main() {
vector<string> arr;
string str;
while (cin >> str) arr.push_back(str);
cout << numUniqueEmails(arr) << endl;
return 0;
}