class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
//seperate string on space , take out value , then seperate on . and get
// all sub domains , make a HM and add (subdomains,value), keep updating the
//value as you iterate the domains array
HashMap<String,Integer> map = new HashMap<>();
for(String domain : cpdomains){
String[] arr = domain.split(" ");
int visited = Integer.parseInt(arr[0]);
//*** exception that split will not recogonize full stop for some reaso
// so add comment lines, some how this works , just remember this ****
String words[] = arr[1].split("\\.");
//making sub domains and adding it to hashmap against their value
StringBuilder word = new StringBuilder();
//keep making domains in reverse and keep adding to map
for(int i = words.length-1 ;i >= 0 ; i--){
if(i == words.length - 1)
word.append(words[i]);
else{
word.insert(0,".");
word.insert(0,words[i]);
}
map.put(word.toString(),map.getOrDefault(word.toString(),0)+visited);
}
}
List<String> ans = new ArrayList<>();
//iterate in hashmap and make answer
for(String key : map.keySet()){
StringBuilder sb = new StringBuilder();
sb.append(map.get(key)+" " + key);
ans.add(sb.toString());
}
return ans;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter