【无标题】一起动手维护代码第3关:P大邮箱的完善性维护

本关任务:在P大的校园网门户中,可以设置除学号外的个性化邮箱名称。
每个邮箱地址都包含一个用户名和一个域名,用@隔开。
例如,在alice@pku.edu.cn中,alice是用户名,pku.edu.cn是域名。
某天,管理门户的老师要求对设置个性化邮箱名称时添加两条过滤规则:

  • 用户名中的.会被忽略掉,例如alice.z@pku.edu.cnalicez@pku.edu.cn被视为相同邮箱账号;
  • 用户名中+及其后面的字符会被忽略掉,例如m.y+name@pku.edu.cnmy@pku.edu.cn被视为相同邮箱账号;

这两种规则可以同时被使用。
现在我们需要维护原来的代码,添加上新的功能,这被称为完善性维护。
请你维护代码,完善numUniqueEmails函数,使得给出一个邮箱地址列表emails,能返回唯一的邮箱地址数量。

样例:

 
  1. 输入多行:
  2. test.email+alex@pku.edu.cn
  3. test.e.mail+bob.cathy@pku.edu.cn
  4. testemail+david@pku.edu.cn
  5. 输出:1
  6. 解释:唯一的邮箱地址是 "testemail@pku.edu.cn"。

相关知识

为了完成本关任务,你需要掌握:1.字符串的处理, 2.哈希表的使用方法

C++中的字符串

通过string关键字声明string对象,常用的函数有size(),substr()等 具体可以查看C++官方文档

 
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. string str = "hello world.";
  5. cout << str.size() << endl;
  6. cout << str << endl;
  7. return 0;
  8. }

输出:

 
  1. 12
  2. hello world.

C++中的哈希表

通过unordered_set<string>声明一个无序集合容器,只存储不同的元素。可以在O(1)的时间复杂度内插入和删除。

示例如下:

 
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. unordered_set<string> s;
  5. s.insert("1");
  6. s.insert("1");
  7. s.insert("2");
  8. s.insert("3");
  9. for (auto ss:s) cout << ss << endl;
  10. return 0;
  11. }

输出:

 
  1. 3
  2. 1
  3. 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;

}

 

 

  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值