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

题目标签: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/

posted @ 2019-05-16 08:51  Jimmy_Cheng  阅读(254)  评论(0编辑  收藏  举报