|
| 1 | +/** |
| 2 | + * 811. Subdomain Visit Count |
| 3 | + * https://leetcode.com/problems/subdomain-visit-count/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A website domain "discuss.leetcode.com" consists of various subdomains. At the top level, we have |
| 7 | + * "com", at the next level, we have "leetcode.com" and at the lowest level, "discuss.leetcode.com". |
| 8 | + * When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains |
| 9 | + * "leetcode.com" and "com" implicitly. |
| 10 | + * |
| 11 | + * A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3" or "rep d1.d2" |
| 12 | + * where rep is the number of visits to the domain and d1.d2.d3 is the domain itself. |
| 13 | + * |
| 14 | + * For example, "9001 discuss.leetcode.com" is a count-paired domain that indicates that |
| 15 | + * discuss.leetcode.com was visited 9001 times. |
| 16 | + * |
| 17 | + * Given an array of count-paired domains cpdomains, return an array of the count-paired domains of |
| 18 | + * each subdomain in the input. You may return the answer in any order. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {string[]} cpdomains |
| 23 | + * @return {string[]} |
| 24 | + */ |
| 25 | +var subdomainVisits = function(cpdomains) { |
| 26 | + const domainCount = new Map(); |
| 27 | + |
| 28 | + for (const cpdomain of cpdomains) { |
| 29 | + const [countStr, domain] = cpdomain.split(' '); |
| 30 | + const count = parseInt(countStr); |
| 31 | + const subdomains = getSubdomains(domain); |
| 32 | + |
| 33 | + for (const subdomain of subdomains) { |
| 34 | + domainCount.set(subdomain, (domainCount.get(subdomain) || 0) + count); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + const result = []; |
| 39 | + for (const [domain, count] of domainCount) { |
| 40 | + result.push(`${count} ${domain}`); |
| 41 | + } |
| 42 | + |
| 43 | + return result; |
| 44 | +}; |
| 45 | + |
| 46 | +function getSubdomains(domain) { |
| 47 | + const parts = domain.split('.'); |
| 48 | + const subdomains = []; |
| 49 | + |
| 50 | + for (let i = 0; i < parts.length; i++) { |
| 51 | + subdomains.push(parts.slice(i).join('.')); |
| 52 | + } |
| 53 | + |
| 54 | + return subdomains; |
| 55 | +} |
0 commit comments