码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 811 Subdomain Visit Count 解题报告

时间:2019-02-07 23:54:35      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:res   return   collect   int   while   联网   count   切片   add   

题目要求

A website domain like "discuss.leetcode.com" consists of various subdomains. At the top level, we have "com", at the next level, we have "leetcode.com", and at the lowest level, "discuss.leetcode.com". When we visit a domain like "discuss.leetcode.com", we will also visit the parent domains "leetcode.com" and "com" implicitly.

Now, call a "count-paired domain" to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be "9001 discuss.leetcode.com".

We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.

题目分析及思路

互联网在访问某个域名的时候也会访问其上层域名,题目给出访问该域名的次数,统计所有域名被访问的次数。可以使用字典统计次数,collections.defaultdict可自行赋值。上层域名采用while循环和字符串切片来访问。

python代码

class Solution:

    def subdomainVisits(self, cpdomains: ‘List[str]‘) -> ‘List[str]‘:

        domain_counts = collections.defaultdict(int)

        for cpdomain in cpdomains:

            count, domain = cpdomain.split()

            count = int(count)

            domain_counts[domain] += count

            while ‘.‘ in domain:

                domain = domain[domain.index(‘.‘)+1 :]

                domain_counts[domain] += count

        return [str(v) + ‘ ‘ + k for k, v in domain_counts.items()]

        

 

LeetCode 811 Subdomain Visit Count 解题报告

标签:res   return   collect   int   while   联网   count   切片   add   

原文地址:https://www.cnblogs.com/yao1996/p/10355636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!