-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSubdomainVisitCount.java
42 lines (40 loc) · 1.43 KB
/
SubdomainVisitCount.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package io.ziheng.hashtable.leetcode;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* LeetCode 811. Subdomain Visit Count
* https://leetcode.com/problems/subdomain-visit-count/
*/
public class SubdomainVisitCount {
public List<String> subdomainVisits(String[] cpdomains) {
if (cpdomains == null || cpdomains.length == 0) {
return new LinkedList<>();
}
Map<String, Integer> aMap = new HashMap<>();
for (String cpdomain : cpdomains) {
int index = cpdomain.indexOf(' ');
int visits = Integer.valueOf(
cpdomain.substring(0, index)
);
String domain = cpdomain.substring(index + 1, cpdomain.length());
for (int i = 0; i < domain.length(); i++) {
if (domain.charAt(i) == '.') {
String subDomain = domain.substring(i + 1, domain.length());
aMap.put(
subDomain,
visits + aMap.getOrDefault(subDomain, 0)
);
}
}
aMap.put(domain, visits + aMap.getOrDefault(domain, 0));
}
List<String> resultList = new LinkedList<>();
for (Map.Entry<String, Integer> entry : aMap.entrySet()) {
resultList.add(entry.getValue() + " " + entry.getKey());
}
return resultList;
}
}
/* EOF */