Use substring() instead of spilt() will be more efficient
46.36 %
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
List<String> result = new ArrayList<>();
if (cpdomains == null || cpdomains.length == 0) return result;
Map<String, Integer> map = new HashMap<>();
for (String domain : cpdomains) {
int count = Integer.valueOf(domain.split(" ")[0]);
String[] strs = domain.split(" ")[1].split("\\.");
String curr = "";
for (int i = strs.length - 1; i >= 0; i--) {
if (curr.length() > 0) curr = "." + curr;
curr = strs[i] + curr;
if (!map.containsKey(curr)) {
map.put(curr, count);
} else {
map.put(curr, map.get(curr) + count);
}
}
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
result.add(entry.getValue() + " " + entry.getKey());
}
return result;
}
}
No comments:
Post a Comment