Leetcode 811. Subdomain Visit Count

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Subdomain Visit Count

2. Solution

  • Version 1
class Solution:
    def subdomainVisits(self, cpdomains):
        stat = {}
        for cpdomain in cpdomains:
            data = cpdomain.split(' ')
            count = int(data[0])
            domain = data[1]
            self.subdomainStat(stat, domain, count)

        result = []
        for key, value in stat.items():
            string = str(value) + ' ' + key
            result.append(string)
        return result


    def subdomainStat(self, stat, domain, count):
        if domain in stat:
            stat[domain] += count
        else:
            stat[domain] = count

        subdomain = domain.split('.', 1)
        if len(subdomain) > 1:
            self.subdomainStat(stat, subdomain[1], count)
  • Version 2
class Solution:
    def subdomainVisits(self, cpdomains):
        stat = {}
        for cpdomain in cpdomains:
            data = cpdomain.split(' ')
            count = int(data[0])
            domain = data[1]
            while True:
                if domain in stat:
                    stat[domain] += count
                else:
                    stat[domain] = count
                subdomain = domain.split('.', 1)
                if len(subdomain) == 1:
                    break
                else:
                    domain = subdomain[1] 

        result = []
        for key, value in stat.items():
            string = str(value) + ' ' + key
            result.append(string)
        return result

Reference

  1. https://leetcode.com/problems/subdomain-visit-count/

你可能感兴趣的:(Leetcode 811. Subdomain Visit Count)