LeetCode之Subdomain Visit Count(K
2020-06-12 本文已影响0人
糕冷羊
问题:
方法:
需要查分域名,然后根据域名的组成结构重新统计每个子域名的数量,通过map结构保存子域名的数量,最后遍历map结构输出结果即可。
class SubdomainVisitCount {
fun subdomainVisits(cpdomains: Array<String>): List<String> {
val map = mutableMapOf<String, Int>()
for (cpdomain in cpdomains) {
val splits = cpdomain.split(" ")
val count = splits[0]
val domain = splits[1]
val subs = domain.split(".")
var subDomain = ""
var index = subs.lastIndex
do {
subDomain = if (index == subs.lastIndex) {
subs[index]
} else {
subs[index] + "." + subDomain
}
val oldCount = map.getOrDefault(subDomain, 0)
map[subDomain] = oldCount + count.toInt()
index--
} while (index >= 0)
}
return map.map { it.value.toString() + " " + it.key }
}
}
fun main(args: Array<String>) {
val input = arrayOf("9001 discuss.leetcode.com")
val subdomainVisitCount = SubdomainVisitCount()
val result = subdomainVisitCount.subdomainVisits(input)
}
有问题随时沟通