A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.
Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".
We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.
Input:
["9001 discuss.leetcode.com"]
Output:
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Explanation:
We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.
Input:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation:
We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.
/**
* @param {string[]} cpdomains
* @return {string[]}
*/
var subdomainVisits = function (cpdomains) {
let map = new Map();
for (let cpdomain of cpdomains) {
let starIdx = 0;
let splitIdx = 0;
let count = 0;
// 제일 앞의 숫자 구분을 위한 구분값
splitIdx = cpdomain.indexOf(' ');
//substring(start,end) => [start:end-1]
count = cpdomain.substring(starIdx, splitIdx);
starIdx = splitIdx + 1;
// endIdx = cpdomain.lastIndexOf('.', starIdx);
for (; splitIdx != -1;) {
// substring의 종료 인덱스가 음수인 경우, 암시적을 마지막 인덱스 할당
cpdomain = cpdomain.substring(starIdx)
starIdx = 0;
let preCount = map.get(cpdomain);
if (preCount == undefined) { // map.get 에서 요소를 찾기 못하는 경우 undefined 반환.
preCount = 0;
}
map.set(cpdomain, Number(count) + preCount);
splitIdx = cpdomain.indexOf('.', starIdx);
starIdx = splitIdx + 1;
}
}
let res = [];
for (let pair of map) {
// console.log(pair[1] + ' ' + pair[0]); // pair[0] : key, pair[1]: value
res.push(pair[1] + ' ' + pair[0]);
}
return res;
};
~.~