代码链接:https://leetcode.cn/problems/subdomain-visit-count/solution/zi-yu-ming-fang-wen-ji-shu-by-leetcode/
哈希映射:对于包含一个 .
的域名 x.y
,我们需要统计的是 x.y
和 y
;对于包含两个 .
的域名 a.b.c
,我们需要统计的是 a.b.c
,b.c
和 c
。在统计这些字符串时,我们可以使用哈希映射(HashMap)。统计结束之后,我们遍历哈希映射并输出结果。
class Solution:
def subdomainVisits(self, cpdomains: List[str]) -> List[str]:
hashmap = {}
for domain in cpdomains:
num = int(domain.split()[0])
frags = domain.split()[1].split(".") # "9001 discuss.leetcode.com"
for i in range(len(frags)):
if '.'.join(frags[i:]) in hashmap:
hashmap['.'.join(frags[i:])] += num
else:
hashmap['.'.join(frags[i:])] = num
return ["{} {}".format(value, key) for key, value in hashmap.items()]
# if domain[-1] in hashmap: # "9001 leetcode.com"
# hashmap[domain[-1]] += num
# else:
# hashmap[domain[-1]] = num
# if '.'.join(domain[-2:]) in hashmap:
# hashmap['.'.join(domain[-2:])] += num
# else:
# hashmap['.'.join(domain[-2:])] = num
# if len(domain) == 3:
# if '.'.join(domain) in hashmap:
# hashmap['.'.join(domain)] += num
# else:
# hashmap['.'.join(domain)] = num
# res = []
# for key, value in hashmap.items():
# res.append(str(value)+' '+ key)
# return res
复杂度分析
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N 是数组 cpdomains 的长度,这里假设 cpdomains 中每个元素的长度都是常数级别的。
- 空间复杂度: O ( N ) O(N) O(N),用于存储哈希映射。