LeetCode 811. Subdomain Visit Count(哈希表的简单运用,c++,python)

2023-11-05

A website domain like “discuss.leetcode.com” consists of various subdomains. At the top level, we have “com”, at the next level, we have “leetcode.com”, and at the lowest level, “discuss.leetcode.com”. When we visit a domain like “discuss.leetcode.com”, we will also visit the parent domains “leetcode.com” and “com” implicitly.

Now, call a “count-paired domain” to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be “9001 discuss.leetcode.com”.

We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.

Example 1:
Input:

["9001 discuss.leetcode.com"]

Output:

["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]

Explanation:
We only have one website domain: “discuss.leetcode.com”. As discussed above, the subdomain “leetcode.com” and “com” will also be visited. So they will all be visited 9001 times.

Example 2::
Input:

["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]

Output:

["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]

Explanation:
We will visit “google.mail.com” 900 times, “yahoo.com” 50 times, “intel.mail.com” once and “wiki.org” 5 times. For the subdomains, we will visit “mail.com” 900 + 1 = 901 times, “com” 900 + 50 + 1 = 951 times, and “org” 5 times.

Notes:
The length of cpdomains will not exceed 100.
The length of each domain name will not exceed 100.
Each address will have either 1 or 2 “.” characters.
The input count in any count-paired domain will not exceed 10000.
The answer output can be returned in any order.

思路:一道很简单的哈希表的运用题,把域名按“.”进行切分,然后将子域名作为键,访问次数作为值存储到哈希表中。如果键已经存在则需要把对应的值进行相加,而不是覆盖。

感觉就是STL库的运用,这里自己写了个split函数,做的逻辑也有点复杂,所以造成速度有些慢。
另外使用unodered_mapmap的速度更快。如下图
在这里插入图片描述
原因:STL中,map 对应的数据结构是 红黑树。红黑树是一种近似于平衡的二叉查找树,里面的数据是有序的。在红黑树上做查找操作的时间复杂度为 O(logN)。而 unordered_map 对应 哈希表,哈希表的特点就是查找效率高,时间复杂度为常数级别 O(1), 而额外空间复杂度则要高出许多。所以对于需要高效率查询的情况,使用 unordered_map 容器。而如果对内存大小比较敏感或者数据存储要求有序的话,则可以用 map 容器。(参考

class Solution {
public:
    vector<string> subdomainVisits(vector<string>& cpdomains) {
        vector<string> ans;//保存答案
        unordered_map<string, int> dic;
        string domain;
        for(int i = 0; i< cpdomains.size(); i++){
            domain = cpdomains[i];
            vector<string> tmp = split(domain, " ");
            int count = stoi(tmp[0]);//次数
            
            vector<string> sub_domains = split(tmp[1], ".");
            for(int j = 0; j<sub_domains.size(); j++){
                string domain_name = sub_domains[j];
                for(int k = j+1; k<sub_domains.size(); k++){
                    domain_name = domain_name+"."+sub_domains[k];
                }
                if(dic.count(domain_name)==1)//map中已经存在
                    dic[domain_name] += count;
                else
                    dic[domain_name] = count;//不存在加入
            }
        }
        unordered_map<string, int>::iterator it = dic.begin();
        for(; it!= dic.end(); it++){
            string tmp;
            tmp = to_string(it->second);
            tmp = tmp + " " + it->first;
            ans.push_back(tmp);
        }
        return ans;
    }
    
    vector<string> split(const string &str, const string &delim){
        vector<string> vec;
        string s = str;
        int index;
        while( (index = s.find(delim)) != -1){
            string tmp = s.substr(0, index);
            vec.push_back(tmp);
            s = s.substr(index+1);
        }
        vec.push_back(s);
        return vec;
    }
};

python中直接使用dic即可,剩下的就是字符串的一些操作

class Solution(object):
    def subdomainVisits(self, cpdomains):
        """
        :type cpdomains: List[str]
        :rtype: List[str]
        """
        dic = {}
        for domain in cpdomains:
            cnt, name = domain.split()
            cnt = int(cnt)
            list_name = name.split('.')
            for i in range(len(list_name)):
                sep = '.'
                tmp_name = sep.join(list_name[i:])
                if tmp_name not in dic:
                    dic[tmp_name] = cnt
                else:
                    dic[tmp_name] += cnt
        ans = ["{} {}".format(value, key) for key, value in dic.items()]
        return ans
        

速度貌似还行
在这里插入图片描述

附录:参考LeetCode讨论区的c++优秀解答

public:
    vector<string> subdomainVisits(vector<string>& cpdomains) {
        vector<string> res;
        unordered_map<string, int> m;
        for(auto &i : cpdomains){
            int num = stoi(i);//c++11新特性,会自动判断字符串中哪些是数字,并把数字部分转换为int
            int lo = i.size() - 1;
            while(i[lo] != ' '){
                if(i[lo] == '.')
                    m[i.substr(lo + 1)] += num;//找到一个子域名
                lo--;
            }
            m[i.substr(lo + 1)] += num;
        }
        for(auto &i : m)
            res.push_back(to_string(i.second) + " " + i.first);
        return res;
    }
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

LeetCode 811. Subdomain Visit Count(哈希表的简单运用,c++,python) 的相关文章

  • gpio相关介绍

    GPIO 通用输入输出端口 gpio的基本输出功能由STM32控制引脚输出高 低电平 实现开关控制 最基本的输入功能是检测外部输入电平 gpio工作模式 输入模式 上拉 下拉 浮空 在输入模式中 施密特触发器打开 输出被禁止 数据寄存器每隔
  • HTML,CSS,Javascript在Web开发中分别起什么作用?

    简单描述HTML CSS Javascript在Web开发中分别起什么作用 1 什么是HTML 超文本标记语言 Hyper Text Markup Language HTML 是用来描述网页的一种语言 2 CSS 层叠样式表 Cascadi
  • VUE联动下拉选择框

  • Javascript中大括号“{}”的多义性

    JS中大括号有四种语义作用语义1 组织复合语句 这是最常见的 if condition else for 语义2 对象直接量声明 var obj name jack age 23 整个是个赋值语句 其中的 name jack age 23

随机推荐

  • 蓝桥杯 空间

    题目1 本题为填空题 只需要算出结果后 在代码中使用输出语句将所填结果输出即可 小蓝准备用 256MB 的内存空间开一个数组 数组的每个元素都是 32 位 二进制整数 如果不考虑程序占用的空间和维护内存需要的辅助空间 请问 256MB 的空
  • IDEA : IDEA好用的插件集锦

    1 Free Mybatis plugin mybatis 插件 让你的mybatis xml像java代码一样编辑 我们开发中使用mybatis时时长需要通过mapper接口查找对应的xml中的sql语句 该插件方便了我们的操作 安装完成
  • 代理IP和Socks5代理:跨界电商与爬虫的智能引擎

    跨界电商 作为全球市场的一部分 对数据的需求越来越大 同时 随着互联网的发展 爬虫技术也在不断演进 成为了跨界电商的关键工具之一 然而 随之而来的是网站的反爬虫机制和网络安全风险 在这种情况下 代理IP和Socks5代理应运而生 为企业提供
  • Java复习(第一季)

    Java的特性与版本 最好的跨平台开源编程语言 第二章 常量和变量 2 1 Java中的关键字 Java关键字是区分大小写的 viod是关键字 但Viod就不是 使用标识符时 需要遵守几条规则 1 标识符可以由字母 数字 下划线 美元符 组
  • Linux初体验—整理了一些Linux的常用命令

    目录 查看当前目录下的内容 文件目录操作命令 作用 用于切换当前工作目录 即进入指定目录 作用 用于显示文件内容 作用 以分页的形式显示文件内容 作用 查看文件末尾内容 作用 创建目录 作用 删除空目录 作用 删除指定文件或目录 作用 用于
  • RGB格式解释说明

    RGB 是一种加色模型 将红 Red 绿 Green 蓝 Blue 三原色的色光以不同的比例相加 以产生多种多样的色光 且三原色的红绿蓝不可能用其他单色光合成 浮点表示方式 取值范围为 0 0 1 0 整数表示 取值范围为 0 255 或者
  • MATLAB算法实战应用案例精讲-【深度学习】CNN池化

    目录 计算机视觉与卷积神经网络 计算机视觉综述 计算机视觉的发展历程 卷积神经网络
  • 狂神ES入门

    视频链接 https www bilibili com video BV17a4y1x7zq 文章目录 一 Elasticsearch与Solr对比 二 环境安装 2 1 Elasticsearch 7 12 1安装 2 2 elastic
  • 7)存储过程

    文章目录 一 存储过程概念 1 存储过程的优点 2 存储过程的类型 二 创建和使用存储过程 1 创建存储过程 2 使用存储过程 3 修改存储过程 4 删除存储过程 一 存储过程概念 就是一条或者多条T SQL 语句的集合 可视为数据库的批处
  • 带注释 实验8-2-3 删除字符 (20分)

    实验8 2 3 删除字符 20分 本题要求实现一个删除字符串中的指定字符的简单函数 函数接口定义 void delchar char str char c 其中char str是传入的字符串 c是待删除的字符 函数delchar的功能是将字
  • Datawhale宣传团队名单公示!

    Datawhale团队 公示 Datawhale宣传团队名单 感谢今年八月所有参与 AI夏令营 的宣传大使 是你们 让更多的同学了解到了开源学习 也让更多人看到了Datawhale 星星之火 可以燎原 社区的发展离不开每一位贡献者 让我们从
  • 浏览器渲染进程的线程有哪些

    浏览器的渲染进程的线程总共有五种 1 GUI渲染线程 负责渲染浏览器页面 解析HTML CSS 构建DOM树 构建CSSOM树 构建渲染树和绘制页面 当界面需要重绘或由于某种操作引发回流时 该线程就会执行 注意 GUI渲染线程和JS引擎线程
  • ueditor百度富文本编辑器粘贴后html丢失class和style样式

    问题 项目经理从123在线编辑上排版好的文章 粘贴到项目的编辑器上 样式完全乱了 排版是这样的 复制到ueditor后的格式 这天差地别呀 于是打开代码模式 发现section的属性全没了 但是 span的属性还是有的 猜测ueditor有
  • Vue样式设置的几种方式

    1 直接使用class设置样式 代码 结果 2 通过v bind绑定class设置样式 1 使用json形式 代码 结果 2 使用数组形式 代码 结果 注意 通过第二种数组的方式 也可以通过三元表达式进行class的判断 此处不再赘述 3
  • 数学建模算法与应用(司守奎版)python 代码实现

    引言 在准备九月份的华为杯 入门选择了司守奎老师的教材 数学建模算法与应用 书中仅提供了lingo和matlab的版本 但是python的数据处理能力更加出色 因此考虑在学习的过程中将代码全部用python实现 第一章 线性规划 基础代码
  • 用 Rust 编写一个简单的词法分析器

    词法分析是编译器和解释器的第一个环节 相对而言也比较简单 词法分析器 有时也称为单元生成器 tokenizer 或者扫描器 scanner 将源代码转换为词法单元 这个过程称为词法分析 本文代码设计复刻自 用Go语言自制解释器 词法分析器一
  • 力扣每日一题——最大间距

    题目链接 class Solution public int maximumGap vector
  • Nodejs全局配置

    在软件的安装 目录下自己新建两个文件夹 node gobal 和 node cache 进入cmd命令行 输入一下的命令设置全局模块的安装路径到node gobal文件夹 缓存到node cache文件夹 npm config set pr
  • C语言-指针变量作为函数参数

    指针变量作为函数参数 函数的参数类型不仅仅是整型 浮点型 字符型也可以是指针类型 它的作用是将一个变量的地址传到另外一个函数中 常见的是传数组的首地址 文章目录 指针变量作为函数参数 一 示例1 二 示例2 三 示例3 提示 以下是本篇文章
  • LeetCode 811. Subdomain Visit Count(哈希表的简单运用,c++,python)

    A website domain like discuss leetcode com consists of various subdomains At the top level we have com at the next level