★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10562647.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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.

Example 1:
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.
Example 2:
Input:
["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]
Output:
["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]
Explanation:
We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times. For the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.

Notes:

  • The length of cpdomains will not exceed 100.
  • The length of each domain name will not exceed 100.
  • Each address will have either 1 or 2 "." characters.
  • The input count in any count-paired domain will not exceed 10000.
  • The answer output can be returned in any order.

一个网站域名,如"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

Runtime: 92 ms
Memory Usage: 19.8 MB
 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var res:[String] = [String]()
 4         var subdomainCnt:[String:Int] = [String:Int]()
 5         for cpdomain in cpdomains
 6         {
 7             var spaceIdx = cpdomain.index(of: " ")!
 8             var cnt:Int = Int(String(cpdomain[cpdomain.startIndex..<spaceIdx])) ?? 0
 9             var rem:String = String(cpdomain[spaceIdx..<cpdomain.endIndex])
10             rem.remove(at:rem.startIndex)
11             for i in 0..<rem.count
12             {
13                 if rem[i] == "."
14                 {
15                     subdomainCnt[rem.subString(i + 1),default:0] += cnt
16                 }
17             }
18             subdomainCnt[rem,default:0] += cnt
19         }
20         for (key,val) in subdomainCnt
21         {
22             res.append(String(val) + " " + key)
23         }
24         return res
25     }
26 }
27
28 //String扩展
29 extension String {
30     //subscript函数可以检索数组中的值
31     //直接按照索引方式截取指定索引的字符
32     subscript (_ i: Int) -> Character {
33         //读取字符
34         get {return self[index(startIndex, offsetBy: i)]}
35     }
36
37     // 截取字符串:从index到结束处
38     // - Parameter index: 开始索引
39     // - Returns: 子字符串
40     func subString(_ index: Int) -> String {
41         let theIndex = self.index(self.endIndex, offsetBy: index - self.count)
42         return String(self[theIndex..<endIndex])
43     }
44 }


92ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var domainDict = Dictionary<String, Int>()
 4         var result = [String]()
 5         for cpdomain in cpdomains {
 6             let domainPair = cpdomain.split(separator: " ")
 7             let count = Int(domainPair[0])!
 8             var domain = String(domainPair[1])
 9             domainDict[domain] = (domainDict[domain] ?? 0) + count
10             while let index = domain.firstIndex(of: ".") {
11                 domain.removeSubrange(domain.startIndex...index)
12                 domainDict[domain] = (domainDict[domain] ?? 0) + count
13             }
14         }
15         for (d, c) in domainDict {
16             result.append("\(c) \(d)")
17         }
18         return result
19     }
20 }


96ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var result = [String: Int]()
 4         cpdomains.forEach { (cpdomain) in
 5             let parts = cpdomain.split(separator: " ")
 6             let times = Int(parts[0]) ?? 0
 7             var domain = String(parts[1])
 8
 9             result[domain] = (result[domain] ?? 0) + times
10
11             while let dotIndex = domain.index(of: ".") {
12                 domain.removeSubrange(domain.startIndex...dotIndex)
13                 result[domain] = (result[domain] ?? 0) + times
14             }
15         }
16         return result.reduce(into: []) { (a, pair) in
17             a.append("\(pair.value) \(pair.key)")
18         }
19     }
20 }


98ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var res = [String: Int]()
 4
 5         for domain in cpdomains {
 6             let splits = domain.split(separator: " ").map { String($0) }
 7             let count = Int(splits[0])!
 8             let domain = splits[1]
 9             let frags = domain.split(separator: ".").map { String($0) }
10             var curr = [String]()
11             for i in Array(0..<frags.count).reversed() {
12                 curr.append(frags[i])
13                 let subdomain = curr.reversed().joined(separator: ".")
14                 res[subdomain] = (res[subdomain] ?? 0) + count
15             }
16          }
17
18         return res.map { "\($0.value) \($0.key)" }
19     }
20 }


100ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var ans = [String : Int]();
 4         for domain in cpdomains {
 5             let t = domain.split(separator: " ")
 6             let count = Int(t[0])!
 7             let domains = t[1].split(separator: ".")
 8             var computedDomain = ""
 9             for s in domains.reversed() {
10                 if computedDomain == "" {
11                     computedDomain = String(s)
12                 } else {
13                     computedDomain = s + "." + computedDomain
14                 }
15                 if let c = ans[computedDomain] {
16                   ans[computedDomain] = count + c
17                 } else {
18                   ans[computedDomain] = count
19                 }
20             }
21         }
22
23         let result = ans.map { (k, v)  in
24             "\(v) \(k)"
25         }
26         return result
27     }
28 }


104ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var dict = [String: Int]()
 4         for domain in cpdomains {
 5             let items = domain.split(separator: " ")
 6             let cpdo = items[1].split(separator: ".")
 7             var key = ""
 8             for i in (0..<cpdo.count).reversed() {
 9                 if i != cpdo.count - 1 {
10                     key = "." + key
11                 }
12                 key = cpdo[i] + key
13                 dict[key] = dict[key] ?? 0
14                 dict[key]! += Int(items[0])!
15             }
16         }
17         var result = [String]()
18         for (key, value) in dict {
19             result.append(String(value) + " " + key)
20         }
21         return result
22     }
23 }


108ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var dict: [String: Int] = [:]
 4         cpdomains.forEach({ countAndDomain in
 5             let count = Int(countAndDomain.split(separator: " ")[0]) ?? 0
 6             var domain = String(countAndDomain.split(separator: " ")[1])
 7             dict[domain] = (dict[domain] ?? 0) + count
 8             while let dotIndex = domain.firstIndex(of: ".") {
 9                 domain.removeSubrange(domain.startIndex...dotIndex)
10                 dict[domain] = (dict[domain] ?? 0) + count
11             }
12         })
13         return dict.reduce([String](), {a, pair in
14             var a = a
15             a.append("\(pair.value) \(pair.key)")
16             return a
17         })
18     }
19 }


116ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var result:[String: Int] = [String: Int]()
 4         for domain in cpdomains {
 5             let split = domain.split(separator: " ")
 6             if let countString = split.first, let count = Int(countString), let domains = split.last {
 7                 let domainComponents = Array(domains.split(separator: ".").reversed())
 8                 for idx in 0..<domainComponents.count {
 9                     let curr = Array(domainComponents[0...idx].reversed())
10                     let currDomain = String(curr.joined(separator: ".")).lowercased()
11                     result[currDomain] = (result[currDomain] ?? 0) + count
12                 }
13             }
14         }
15
16         var answer: [String] = [String]()
17         for (key, val) in result {
18             answer.append("\(val) \(key)")
19         }
20         return answer
21     }
22 }


144ms

 1 class Solution {
 2   func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3     var results: [String:Int] = [:]
 4     cpdomains.forEach { domain in
 5       let splited = domain.components(separatedBy: " ")
 6       if splited.count > 1 {
 7         let counter = splited[0]
 8         let splitedDomain = splited[1]
 9
10         let dots = splitedDomain.components(separatedBy: ".")
11         for i in 0..<(dots.count) {
12           var d = dots[i]
13           for j in (i+1)..<dots.count {
14             d += "." + dots[j]
15           }
16           results[d] = (Int(counter) ?? 0) + (results[d] ?? 0)
17         }
18       }
19     }
20     return results.map { String($0.1) + " " + $0.0 }
21   }
22 }


156ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3         var dict = [String: Int]()
 4         for e in cpdomains {
 5             let c = e.components(separatedBy: " ")
 6             let count = Int(c[0])!
 7             let domain = c[1]
 8             let subdomains = domain.components(separatedBy: ".")
 9             for i in subdomains.indices {
10                 let sub = subdomains[i...].joined(separator: ".")
11                 dict[sub, default: 0] += count
12             }
13         }
14         return dict.map { "\($0.value) \($0.key)"}
15     }
16 }


172ms

 1 class Solution {
 2     func subdomainVisits(_ cpdomains: [String]) -> [String] {
 3       var res = [String]()
 4       var dict = [String: Int]()
 5        for cpdomain in cpdomains {
 6            let visit = retrieveCount(cpdomain)
 7            let count = Int(visit) ?? 0
 8            let domain = retrieveDomain(cpdomain)
 9            var subdomains = domain.components(separatedBy: ".")
10            while (subdomains.count > 0) {
11                let str = subdomains.joined(separator: ".")
12                if var visited = dict[str] {
13                    visited += count
14                    dict.updateValue(visited, forKey: str)
15                } else {
16                    dict.updateValue(count, forKey: str)
17                }
18                subdomains.removeFirst()
19            }
20        }
21
22        for subdomain in dict.keys {
23            let visits = dict[subdomain] ?? 0
24            let cpdomain = String(visits) + " " + subdomain
25            res.append(cpdomain)
26        }
27       return res
28     }
29
30     func retrieveDomain(_ cpdomain: String) -> String {
31         let parts = cpdomain.components(separatedBy: " ")
32         return parts.last ?? ""
33     }
34
35     func retrieveCount(_ cpdomain: String) -> String {
36         let parts = cpdomain.components(separatedBy: " ")
37         return parts.first ?? ""
38     }
39 }

转载于:https://www.cnblogs.com/strengthen/p/10562647.html

[Swift]LeetCode811. 子域名访问计数 | Subdomain Visit Count相关推荐

  1. LeetCode每日一题——811. 子域名访问计数

    LeetCode每日一题系列 题目:811. 子域名访问计数 难度:普通 文章目录 LeetCode每日一题系列 题目 示例 思路 题解 题目 网站域名 "discuss.leetcode. ...

  2. LeetCode·每日一题·811.子域名访问计数·哈希

    链接:https://leetcode.cn/problems/subdomain-visit-count/solution/-by-xun-ge-v-i3sb/ 来源:力扣(LeetCode) 著作 ...

  3. Leetcode811.Subdomain Visit Count子域名访问计数

    一个网站域名,如"discuss.leetcode.com",包含了多个子域名.作为顶级域名,常用的有"com",下一级则有"leetcode.com ...

  4. LeetCode Algorithm 811. 子域名访问计数

    Ideas 计数配对域名是由域名访问次数和域名组成的,那么对应域名的每一级域名都访问了相应次. 那么我们可以遍历计数配对域名组成的数组,对于每个计数配对域名,可以先把域名按照.分隔开,然后由一个总的计 ...

  5. LeetCode 811. 子域名访问计数

    1. 题目 一个网站域名,如"discuss.leetcode.com",包含了多个子域名. 作为顶级域名,常用的有"com",下一级则有"leetc ...

  6. LeetCode(811)——子域名访问计数(JavaScript)

    一个网站域名,如"discuss.leetcode.com",包含了多个子域名.作为顶级域名,常用的有"com",下一级则有"leetcode.com ...

  7. C#LeetCode刷题之#811-子域名访问计数​​​​​​​(Subdomain Visit Count)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3814 访问. 一个网站域名,如"discuss.lee ...

  8. nginx使用子域名访问指定端口

    添加配置 cd /etc/nginx/conf.dvi api.conf 找到server修改配置文件如下 server{server_name walking.example.com;locatio ...

  9. 将域名绑定到ip上,并实现访问不同二级子域名对应不同目录

    一.将域名绑定到ip上 1.环境介绍:阿里云服务器ESC(美国硅谷) 2.购买域名 3.备案 注:由于我买的是美国地区服务器,所以不用备案,如果买的国内服务器,这里需要添加一个备案操作. 4.域名实名 ...

最新文章

  1. c# 实现 加减乘除
  2. C项目实践--俄罗斯方块(2)
  3. 浅谈数据中的偏差问题和推荐系统去偏最新研究进展
  4. c语言第一次作业,C语言培训班第一次作业 (1)
  5. Launch custom android application from android browser
  6. Django里URL配置中name参数的作用
  7. poj 1094 Sorting It All Out 很好的拓扑排序,让我对拓扑排序有了一个很好的写法!!!
  8. 一、CRUB的使用及如何终端关机
  9. 混合游戏环境:让人类一直身处在物联网中(作业 全靠google)
  10. 牛客小白月赛2 H 武 【Dijkstra】
  11. 嵌入式研发人员核心竞争力分析
  12. 手机企业邮箱客户端哪个好用?
  13. Kali linux 学习笔记(二)环境优化(网络配置、软件安装、显卡优化、线程限制、电源优化) 2020.2.12
  14. Nginx Rewrite的讲解(从新手村到小有成就7)
  15. 大厂面试必考题:三行布局之圣杯布局和双飞翼布局的区别
  16. Spring实训 个人博客二 详情页
  17. java学习个人总结_Java学习的总结
  18. 计算机考研真题解析---计算机网络
  19. 基于javaweb的旅游管理系统(java+jsp+html5+bootstrap+servlet+mysql)
  20. cms php 带商城系统下载,开源免费PHP商城CMS系统集合

热门文章

  1. 首个由国内发起的分布式消息领域的国际标准OpenMessaging一周年回顾
  2. Python数据结构与算法--数据类型
  3. linux下单独安装oracle12.1客户端
  4. Python数据结构——栈、队列的实现(一)
  5. 使用Capistrano向EC2部署Django代码--关于SSH相关的配置
  6. gdb调试器命令(zz)
  7. 在C#程序设计中使用Win32 API
  8. Linux Shell常用技巧(八)
  9. TortoiseSVN Launch Failed Error:系统找不到指定路径
  10. android 监听手机开机