原题链接

解题思路:

1. 第一步,通过空格分割数字与域名
2. 分割出的域名再用点继续分割,分割出子域名
3. 结果集存入字典,每次拿到子域名后更新下计数
4. 遍历字典,把最终结果拼接成字符串

golang示例代码

 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
func subdomainVisits(cpdomains []string) []string {
    dict := make(map[string]int)
    for _, str := range cpdomains {
        firsts := strings.Split(str, " ")
        _cnt, domain := firsts[0], firsts[1]
        cnt, _ := strconv.Atoi(_cnt)
        // 下一步继续分割domain
        domains := strings.Split(domain, ".")
        var otherDomain string
        for i := len(domains) - 1; i >= 0; i-- {
            otherDomain = fmt.Sprintf("%s.%s", domains[i], otherDomain)
            if _, ok := dict[otherDomain]; ok {
                dict[otherDomain] += cnt
            } else {
                dict[otherDomain] = cnt
            }
        }
    }
    var results []string
    for key, value := range dict {
        // 最后会多一个.字符,舍弃不用即可
        results = append(results, fmt.Sprintf("%d %s", value, key[:len(key) - 1]))
    }
    return results
}