1. 程式人生 > >LeetCode 811 Subdomain Visit Count 解題報告

LeetCode 811 Subdomain Visit Count 解題報告

bsp ext evel amp int site xpl rep present

題目要求

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 解題報告