811. Subdomain Visit Count

原文地址: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 collectionscollections库的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()]

知识点:

  1. collections.Counter()方法计数器是一个常用的功能需求。
  2. .format()格式化输出很简化代码
所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode
    原文作者:fred_33c7
    原文地址: https://www.jianshu.com/p/5d79b775f0a5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞