在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string array Example 1: Input: Example 2: Input: Example 3: Input: 给定一个字符串数组 示例 1: 输入: 示例 2: 输入: 示例 3: 输入: 332 ms
1 class Solution { 2 func maxProduct(_ words: [String]) -> Int { 3 if words.isEmpty { 4 return 0 5 } 6 7 let products = words.map{ProductHelper($0)} 8 9 var res = 0 10 11 for i in 0..<products.count { 12 for j in i+1..<products.count { 13 let p1 = products[i] 14 let p2 = products[j] 15 if p1.characters & p2.characters == 0 { 16 res = max(p1.count * p2.count, res) 17 } 18 } 19 } 20 21 return res 22 } 23 } 24 25 class ProductHelper { 26 let count : Int 27 let characters : Int 28 init(_ s : String) { 29 count = s.count 30 let arr = s.unicodeScalars 31 var r = 0 32 for c in arr { 33 r |= 1 << Int(c.value - 97) 34 } 35 characters = r 36 } 37 } 804ms 1 class Solution { 2 func maxProduct(_ words: [String]) -> Int { 3 let aValue = "a".unicodeScalars.first!.value 4 if words.count <= 1 { return 0 } 5 var array = [Int]() 6 for word in words { 7 var a = 0 8 for c in word.unicodeScalars { 9 a = a | (1 << (c.value - aValue)) 10 } 11 array.append(a) 12 } 13 14 var result = 0 15 for i in 0 ..< array.count - 1 { 16 for j in 1 ..< array.count { 17 if array[i] & array[j] > 0 { 18 continue 19 } 20 result = max(result, words[i].count * words[j].count) 21 } 22 } 23 return result 24 } 25 }
|
请发表评论