美文网首页
LeetCode之Subdomain Visit Count(K

LeetCode之Subdomain Visit Count(K

作者: 糕冷羊 | 来源:发表于2020-06-12 11:20 被阅读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)
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Subdomain Visit Count(K

          本文链接:https://www.haomeiwen.com/subject/fudgtktx.html