Leetcode 811. Subdomain Visit Count | | Leetcode 811. Subdomain Visit Count 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution Version 1 12345678910111213141516171819202122232425class 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 1234567891011121314151617181920212223class 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 https://leetcode.com/problems/subdomain-visit-count/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏