811. Subdomain Visit Count
2018-06-28 本文已影响4人
fred_33c7
原文地址:https://leetcode.com/problems/subdomain-visit-count/description/
大意:本题比较繁琐。类似于分类然后算加减法。
class Solution:
def subdomainVisits(self, cpdomains):
"""
:type cpdomains: List[str]
:rtype: List[str]
"""
dic = {}
for item in cpdomains:
number = int(item.split(' ')[0])
domains = item.split(' ')[1].split('.')
times = len(domains)
for time in range(times):
key = '.'.join(domains[time:])
n = number
if key in dic:
dic[key] += n
else:
dic[key] = n
out = []
for key, val in dic.items():
out.append(str(val) + ' ' + str(key))
return out
a = Solution()
print(a.subdomainVisits(["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]))
另外,可以用import collections
用collections
库的Counter()
来计数
def subdomainVisits2(self, cpdomains):
ans = collections.Counter()
for domain in cpdomains:
count, domain = domain.split()
count = int(count)
frags = domain.split('.')
for i in xrange(len(frags)):
ans[".".join(frags[i:])] += count
return ["{} {}".format(ct, dom) for dom, ct in ans.items()]
知识点:
-
collections.Counter()
方法计数器是一个常用的功能需求。 -
.format()
格式化输出很简化代码