题目
代码部分一(23ms 89.75%)
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
List<String> res = new ArrayList<>();
Map<String, Integer> map =new HashMap<>();
for(int i = 0; i < cpdomains.length; i++){
String[] str = cpdomains[i].split(" ");
int times = Integer.valueOf(str[0]);
String temp = str[1];
while(temp.indexOf(".") != -1){
map.put(temp, map.getOrDefault(temp, 0) + times);
temp = temp.substring(temp.indexOf(".") + 1);
}
map.put(temp, map.getOrDefault(temp, 0) + times);
}
for(String s: map.keySet()){
res.add(map.get(s) + " " + s);
}
return res;
}
}
代码部分二(16ms 99.37%)
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> map = new HashMap<>();
for(String domain : cpdomains){
if(domain.length() == 0) continue;
int indexofspace = domain.indexOf(' ');
int times = Integer.valueOf(domain.substring(0, indexofspace));
domain = domain.substring(indexofspace + 1);
map.put(domain, map.getOrDefault(domain, 0) + times);
while(domain.indexOf('.') != -1){
domain = domain.substring(domain.indexOf('.') + 1);
map.put(domain, map.getOrDefault(domain, 0) + times);
}
}
List<String> res = new ArrayList<>();
for(Map.Entry<String, Integer> entry : map.entrySet()){
String s = entry.getValue() + " " + entry.getKey();
res.add(s);
}
return res;
}
}