811. Subdomain Visit Count
https://leetcode.com/problems/subdomain-visit-count/
js
/**
* @param {string[]} cpdomains
* @return {string[]}
*/
var subdomainVisits = function(cpdomains) {
const map = {}
cpdomains.forEach(cpdomain => {
const [count, domain] = cpdomain.split(' ')
domain.split('.').reduceRight((ret, seg) => {
ret.unshift(seg)
const key = ret.join('.')
map[key] = (map[key] || 0) + Number(count)
return ret
}, [])
})
return Object.keys(map).map(key => `${map[key]} ${key}`)
}
py
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
data = {}
for cpdomain in cpdomains:
count, domain = cpdomain.split(' ')
domain = domain.split('.')[::-1]
key = ''
for seg in domain:
key = seg if not key else (seg + '.' + key)
data[key] = data.get(key, 0) + int(count)
return ['%d %s' % (v, k) for k, v in data.items()]