https://leetcode.com/problems/subdomain-visit-count

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* @param {string[]} cpdomains
* @return {string[]}
*/

var subdomainVisits = function(cpdomains) {
// ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
let domainWrap = {
result: {},
addCount: function(domain, count) {
if(!this.result[domain]) {
this.result[domain] = count;
} else {
this.result[domain] = this.result[domain] + count;
}
}
};
for(let i=0; i<cpdomains.length; i++) {
const cpdomainsArray = cpdomains[i].split(' ');
let count = parseInt(cpdomainsArray[0]);
let domain = cpdomainsArray[1];
if(domain.match(/\w*\.\w*\.\w*/i)) {
let keywords = domain.split('\.');
domainWrap.addCount(domain, count);
domainWrap.addCount(`${keywords[1]}.${keywords[2]}`, count);
domainWrap.addCount(`${keywords[2]}`, count);

} else if(domain.match(/\w*\.\w*/i)) {
let keywords = domain.split('\.');
domainWrap.addCount(domain, count);
domainWrap.addCount(`${keywords[1]}`, count);
} else {
domainWrap.addCount(domain, count);
}
}

// console.log(domainWrap.result);
return Object.keys(domainWrap.result).map(key => `${domainWrap.result[key]} ${key}`);
};

Comment