1. 程式人生 > >子域名訪問計數 Subdomain Visit Count

子域名訪問計數 Subdomain Visit Count

一個網站域名,如"discuss.leetcode.com",包含了多個子域名。作為頂級域名,常用的有"com",下一級則有"leetcode.com",最低的一級為"discuss.leetcode.com"。當我們訪問域名"discuss.leetcode.com"時,也同時訪問了其父域名"leetcode.com"以及頂級域名 "com"。

給定一個帶訪問次數和域名的組合,要求分別計算每個域名被訪問的次數。其格式為訪問次數+空格+地址,例如:"9001 discuss.leetcode.com"。

接下來會給出一組訪問次數和域名組合的列表cpdomains 。要求解析出所有域名的訪問次數,輸出格式和輸入格式相同,不限定先後順序。

class Solution {     public List<String> subdomainVisits(String[] cpdomains) {         List<String> list = new ArrayList<String>();         Map<String, Integer> map = new HashMap<String, Integer>();         for (int i = 0; i < cpdomains.length; i++) {             String[] s = cpdomains[i].split(" ");             if(map.containsKey(s[1])){                 map.put(s[1], Integer.parseInt(s[0])+map.get(s[1]));             }else{                 map.put(s[1], Integer.parseInt(s[0]));             }                              int index1 = s[1].indexOf(".");             s[1] = s[1].substring(index1 +1);                          if(map.containsKey(s[1]) && index1 != -1){                 map.put(s[1], Integer.parseInt(s[0])+map.get(s[1]));             }else if(!map.containsKey(s[1]) && index1 != -1){                 map.put(s[1], Integer.parseInt(s[0]));             }             if(index1 == -1 ) break;             int index2 = s[1].indexOf(".");             s[1] = s[1].substring(index2 +1);             if(map.containsKey(s[1])&& index2 !=-1){                 map.put(s[1], Integer.parseInt(s[0])+map.get(s[1]));             }else if(!map.containsKey(s[1])&& index2 !=-1){                 map.put(s[1], Integer.parseInt(s[0]));             }         }         for(Map.Entry<String, Integer> m:map.entrySet()){             StringBuffer sb = new StringBuffer();             sb.append(m.getValue().toString()).append(" ").append(m.getKey());             list.add(sb.toString());         }         return list;     } }