LeetCode 811. Subdomain Visit Count (子域名访问计数)

本文介绍了一种高效解决子域名及其所有父级域名计数问题的方法,利用HashMap存储每个域名及其子域名的访问次数,最终输出每个域名的总访问量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目标签:HashMap

  题目给了我们一组域名,让我们把每一个域名,包括它的子域名,计数。

  遍历每一个域名,取得它的计数,然后把它的所有子域名和它自己,存入hashmap,域名作为key,计数作为value。

  最后遍历keyset,把计数和域名重新组合加入result,具体请看code。

 

Java Solution:

Runtime: 7 ms, faster than 99.54% 

Memory Usage: 36.4 MB, less than 99.04%

完成日期:03/15/2019

关键点:hashmap

class Solution 
{
    public List<String> subdomainVisits(String[] cpdomains) 
    {
        // saving each domains including subdomain into map with its count
        Map<String, Integer> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        // iterate each domain
        for(String str : cpdomains)
        {
            int index = str.indexOf(" ");
            // get count frist
            int count = Integer.parseInt(str.substring(0, index));
            // get domain and its subdomains
            String domains = str.substring(index + 1);
            
            do {
                index = domains.indexOf(".");
                
                map.put(domains, map.getOrDefault(domains, 0) + count);
                
                if(index > 0) // means still having more subdomain
                {
                    domains = domains.substring(index + 1);
                }
                
            } while(index > 0); // if index == -1, it means reaching to the end
        }
        
        for(String str : map.keySet())
        {
            result.add(map.get(str) + " " + str);
        }
        
        return result;
    }
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

转载于:https://www.cnblogs.com/jimmycheng/p/10873534.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值