❝
这是一道 「中等难度」 的题
https://leetcode.cn/problems/subdomain-visit-count/❞
题目
网站域名 "" 由多个子域名组成。顶级域名为 "" ,二级域名为 "" ,最低一级为 "" 。当访问域名 "" 时,同时也会隐式访问其父域名 "" 以及 "" 。
「计数配对域名」 是遵循 " " 或 " " 格式的一个域名表示,其中 表示访问域名的次数, 为域名本身。
例如," " 就是一个 「计数配对域名」 ,表示 被访问了 次。
给你一个 「计数配对域名」 组成的数组 ,解析得到输入中每个子域名对应的 「计数配对域名」 ,并以数组形式返回。可以按 「任意顺序」 返回答案。
示例 1:
func subdomainVisits(cpdomains []string) []string {
accessMap := map[string]int{}
for _, cpdomain := range cpdomains {
splits := strings.Split(cpdomain, " ")
countStr := splits[0]
count, _ := strconv.Atoi(countStr)
domain := splits[1]
countDomain(domain, count, accessMap)
}
ans := make([]string, 0, len(accessMap))
for domain, count := range accessMap {
ans = append(ans, strconv.Itoa(count) + " " + domain)
}
return ans
}
func countDomain(domain string, count int, accessMap map[string]int) {
accessMap[domain] += count
index := strings.IndexByte(domain, '.')
if index == -1 {
return
}
countDomain(domain[index + 1 :], count, accessMap)
}
复杂度分析
-
时间复杂度: ,
N为给定数组cpdomains的大小;M为给定的这些域名可以分解出的域名个数的最大值,如域名"discuss.leetcode.com"可以分解出3个域名用于计数。 -
空间复杂度: ,
K为所有参与计数的域名个数,小于等于NM。
- End -
本篇文章来源于微信公众号: i余数
微信扫描下方的二维码阅读本文


Comments NOTHING