LeetCode:811. Subdomain Visit Count

問題:
A website domain like “discuss.leetcode.com” consists of various subdomains. At the top level, we have “com”, at the next level, we have “leetcode.com”, and at the lowest level, “discuss.leetcode.com”. When we visit a domain like “discuss.leetcode.com”, we will also visit the parent domains “leetcode.com” and “com” implicitly.
Now, call a “count-paired domain” to be a count (representing the number of visits this domain received), followed by a space, followed by the address. An example of a count-paired domain might be “9001 discuss.leetcode.com”.
We are given a list cpdomains of count-paired domains. We would like a list of count-paired domains, (in the same format as the input, and in any order), that explicitly counts the number of visits to each subdomain.

範例:

Input: 
["9001 discuss.leetcode.com"]
Output: 
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
Explanation: 
We only have one website domain: "discuss.leetcode.com". As discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.

解法:
這題是計算訪問子domain的次數,在網路上訪問某個域名的時候,也會訪問到上層的域名
像是訪問google.com時,也會訪問到.com這個域

遇到這種唯一值計算的時候
就要動到map登場啦
另外就是要想辦法操作string當作map的key,加上次數作為value
這時候如果熟Golang的strings包就很快完成了

func subdomainVisits(cpdomains []string) []string {
    urlMap := make(map[string]int)
	for _, singleData := range cpdomains {
		data := strings.Split(singleData, " ")
		times, _ := strconv.Atoi(data[0])
		url := data[1]

		sepURL := strings.Split(url, ".")

		subDomains := make([]string, 0, 10)
		for i := 0; i < len(sepURL); i++ {
			subDomains = append(subDomains, strings.Join(sepURL[i:], "."))
		}

		for _, domain := range subDomains {
			if _, ok := urlMap[domain]; ok {
				urlMap[domain] += times
			} else {
				urlMap[domain] = times
			}
		}
	}
	result := make([]string, 0, 100)
	for k, v := range urlMap {
		result = append(result, strconv.Itoa(v)+" "+k)
	}
	return result
}

發佈留言