Leetcode 811. Subdomain Visit Count

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

1. Description

Subdomain Visit Count

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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/
如果有收获,可以请我喝杯咖啡!