[Swift]LeetCode811. 子域名訪問計數 | Subdomain Visit Count

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-mvjniish-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git

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".github

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.web

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"。app

接下來會給出一組訪問次數和域名組合的列表cpdomains 。要求解析出全部域名的訪問次數,輸出格式和輸入格式相同,不限定前後順序。dom

示例 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 }
相關文章
相關標籤/搜索