Q47 Subdomain Visit Count - LeetCode
Mon Jan 30 2023 12:23:47 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
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;
}
}
content_copyCOPY
https://leetcode.com/problems/subdomain-visit-count/
Comments