| 1 | class Solution { |
| 2 | public List<String> subdomainVisits(String[] cpdomains) { |
| 3 | // https://leetcode.com/problems/subdomain-visit-count/discuss/121738/C%2B%2BJavaPython-Easy-Understood-Solution |
| 4 | Map<String, Integer> map = new HashMap(); |
| 5 | for (String cpdomain : cpdomains) { |
| 6 | int i = cpdomain.indexOf(' '); |
| 7 | int n = Integer.valueOf(cpdomain.substring(0, i)); |
| 8 | String domain = cpdomain.substring(i + 1); |
| 9 | for (i = 0; i < domain.length(); ++i) { |
| 10 | if (domain.charAt(i) == '.') { |
| 11 | String d = domain.substring(i + 1); |
| 12 | map.put(d, map.getOrDefault(d, 0) + n); |
| 13 | } |
| 14 | } |
| 15 | map.put(domain, map.getOrDefault(domain, 0) + n); |
| 16 | } |
| 17 | |
| 18 | List<String> res = new ArrayList(); |
| 19 | for (String domain : map.keySet()) res.add(map.get(domain) + " " + domain); |
| 20 | return res; |
| 21 | } |
| 22 | } |