zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    LeetCode:204. 计数质数
    LeetCode:203. 移除链表元素
    LeetCode:202. 快乐数
    LeetCode:191. 位1的个数
    LeetCode:190. 颠倒二进制位
    LeetCode:189. 旋转数组
    LeetCode:187. 重复的DNA序列
    LeetCode:165. 比较版本号
    LeetCode:164. 最大间距
    LeetCode:155. 最小栈
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/10873534.html
Copyright © 2011-2022 走看看