一個網站域名,如"discuss.leetcode.com",包含了多個子域名。作爲頂級域名,常用的有"com",下一級則有"leetcode.com",最低的一級爲"discuss.leetcode.com"。當我們訪問域名"discuss.leetcode.com"時,也同時訪問了其父域名"leetcode.com"以及頂級域名 "com"。
給定一個帶訪問次數和域名的組合,要求分別計算每個域名被訪問的次數。其格式爲訪問次數+空格+地址,例如:"9001 discuss.leetcode.com"。
接下來會給出一組訪問次數和域名組合的列表cpdomains
。要求解析出所有域名的訪問次數,輸出格式和輸入格式相同,不限定先後順序。
示例 1:
輸入:
["9001 discuss.leetcode.com"]
輸出:
["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"]
說明:
例子中僅包含一個網站域名:"discuss.leetcode.com"。按照前文假設,子域名"leetcode.com"和"com"都會被訪問,所以它們都被訪問了9001次。
示例 2
輸入:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
輸出:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
說明:
按照假設,會訪問"google.mail.com" 900次,"yahoo.com" 50次,"intel.mail.com" 1次,"wiki.org" 5次。
而對於父域名,會訪問"mail.com" 900+1 = 901次,"com" 900 + 50 + 1 = 951次,和 "org" 5 次。
注意事項:
-
cpdomains
的長度小於100
。 - 每個域名的長度小於
100
。 - 每個域名地址包含一個或兩個"."符號。
- 輸入中任意一個域名的訪問次數都小於
10000
。
思路:簡單的遍歷,用map保存可能域名,value爲出現次數。
import (
"strings"
"strconv"
)
func subdomainVisits(cpdomains []string) []string {
map1 := make(map[string]int)
for i:=0;i<len(cpdomains);i++ {
res := strings.Split(cpdomains[i], " ")
num,_:=strconv.Atoi(res[0])
str := res[1]
list_str := strings.Split(str, ".")
length := len(list_str)
tmp := ""
for i:=0;i<length;i++{
if tmp != ""{
tmp = list_str[length-i-1] + "."+tmp
}else{
tmp = list_str[length-i-1]
}
if _, ok := map1[tmp]; ok{
map1[tmp] += num
}else{
map1[tmp] = num
}
}
}
var result []string
for k,v := range map1{
result = append(result, strconv.Itoa(v)+" "+k)
}
return result
}
熟悉了一下go寫法