Leetcode 811. Subdomain Visit Count

2021-03-02 16:30:36 浏览数 (1)

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

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞