[Swift]LeetCode811. 子域名访问计数 | 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.

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 }

 

上一篇:DRF节流组件


下一篇:【剑指offer】机器人的运动范围(回溯)