zoukankan      html  css  js  c++  java
  • 811. 子域名访问计数『简单』

    题目来源于力扣(LeetCode

    一、题目

    811. 子域名访问计数

    题目相关标签:哈希表

    注意:

    • cpdomains 的长度小于 100
    • 每个域名的长度小于100
    • 每个域名地址包含一个或两个"."符号。
    • 输入中任意一个域名的访问次数都小于10000

    二、解题思路

    1. 创建哈希表用于记录 cpdomains 中各域名及其子域名出现的次数,键为域名,值为该域名被访问的次数

    2. 据题意:在一个域名中,顶级域名被访问多少次,其子域名被访问的次数也相同

    3. 通过 map 来记录各域名的出现次数,遍历时当 map 中存在该域名时,则访问次数 = map 中记录的次数 + 本次遍历中获取到的访问次数

    4. 通过字符串的 indexOf 方法来查找出一个顶级域名中的各个子域名

    5. 最后遍历 map 将结果以字符串形式添加到 list 结果集

    三、代码实现

    public static List<String> subdomainVisits(String[] cpdomains) {
        // 存储结果集
        List<String> list = new ArrayList<>();
        // 哈希表记录域名及其访问次数,域名为键,次数为值
        Map<String, Integer> map = new HashMap<>();
        for (String str : cpdomains) {
            String[] strs = str.split(" ");
            // 次数
            int count = Integer.valueOf(strs[0]);
            // 域名
            String domains = strs[1];
            // 域名本身存储到 map 中
            map.put(domains, map.getOrDefault(domains, 0) + count);
            int index = domains.indexOf(".");
    
            while (index > -1) {
                // 下一级子域名
                domains = domains.substring(index + 1);
                map.put(domains, map.getOrDefault(domains, 0) + count);
                index = domains.indexOf(".");
            }
        }
        // 遍历 map,将键值添加到 list 中
        for (String s : map.keySet()) {
            // 访问次数 + 空格 + 域名
            list.add(map.get(s) + " " + s);
        }
        return list;
    }
    

    四、执行用时

    五、部分测试用例

    public static void main(String[] args) {
        String[] cpdomains = {"9001 discuss.leetcode.com"};
        // output:{"9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"}
    
    //    String[] cpdomains = {"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"}
        
        List<String> result = subdomainVisits(cpdomains);
        System.out.println(result);
    }
    
  • 相关阅读:
    黄聪:C#中CefSharp的简单使用
    ArcGIS Pro关闭窗口和退出
    AddOverlay
    ArcGIS Pro固定纸张限定比例尺自动调整纵横打印
    ArcGIS pro增加一个独立表到地图
    ArcGIS Pro How to remove standalone table from contents
    ArcGIS Pro的进度条
    CreatePolygonGraphicElement
    Creating a Group with a List of Elements
    ArcGISPro理解多线程
  • 原文地址:https://www.cnblogs.com/zhiyin1209/p/12969049.html
Copyright © 2011-2022 走看看