leetcede2022/10/5日题记

前言

在刷题中学习语言.

2022/10/5
leetcode每日一题:
题目代号 811

问题描述:

子域名访问记数这里是引用

输入输出示例

引用leetcode

问题解析:

  1. 首先遍历获取字串
  2. 截取字串中的访问次数rep和域名
  3. 通过map函数对获取的域名访问数进行统计
  4. 重新将map中的数据转化为vector格式

实现代码:

官方题解

代码如下(官方题解):

class Solution { 
public:
    vector<string> subdomainVisits(vector<string>& cpdomains) {
        vector<string> ans;
        unordered_map<string, int> counts;	//采用哈希表存储结构的map容器,不具备map容器的自动排序功能//本题中不要求排序,只进行记录即可,故选用unordered_map
        for (auto &&cpdomain : cpdomains) {
            int space = cpdomain.find(' ');//找到" "的索引
            int count = stoi(cpdomain.substr(0, space));
            //通过substr()函数复制返回 0->space 之间的子字符串
            //通过stoi()将字符串转化为整数
            string domain = cpdomain.substr(space + 1);//获取" "后的子字符串
            counts[domain] += count;//记录访问次数
            for (int i = 0; i < domain.size(); i++) {
                if (domain[i] == '.') {//遍历"."获取子域名,父域名
                    string subdomain = domain.substr(i + 1);
                    counts[subdomain] += count;
                }
            }
        }
        for (auto &&[subdomain, count] : counts) {
            ans.emplace_back(to_string(count) + " " + subdomain);
        }
        return ans;
    } };

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/subdomain-visit-count/solution/zi-yu-ming-fang-wen-ji-shu-by-leetcode-s-0a6i/
来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ```

我的题解

class Solution {
public:
    vector<string> subdomainVisits(vector<string>& cpdomains) {
        map<string,int> m;
        for(auto s:cpdomains){
            stringstream out(s);//使用stringstream流进行数字转换
            int n;
            string s1;
            out>>n>>s1;
            m[s1]+=n;
            for(int i=0;i<s1.size();i++){
                if(s1[i]=='.'){
                    m[s1.substr(i+1)]+=n;
                }
            }
        }
        vector<string> res;
        for(auto it:m)
            res.push_back(to_string(it.second)+" "+it.first);
            return res;
    }
};

测试

在这里插入图片描述

参考文档:

unordered_map
substr()
stoi()

总结

get到了新的容器和方法,开心😎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

twfplayer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值