Skip to content

Commit 4cca69a

Browse files
authored
feat: add swift implementation to lcof2 problem: No.005 (#2975)
1 parent d55fd17 commit 4cca69a

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

lcof2/剑指 Offer II 005. 单词长度的最大乘积/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,34 @@ function maxProduct(words: string[]): number {
181181
}
182182
```
183183

184+
#### Swift
185+
186+
```swift
187+
class Solution {
188+
func maxProduct(_ words: [String]) -> Int {
189+
let n = words.count
190+
var masks = [Int](repeating: 0, count: n)
191+
192+
for i in 0..<n {
193+
for c in words[i] {
194+
masks[i] |= 1 << (c.asciiValue! - Character("a").asciiValue!)
195+
}
196+
}
197+
198+
var maxProduct = 0
199+
for i in 0..<n {
200+
for j in i+1..<n {
201+
if masks[i] & masks[j] == 0 {
202+
maxProduct = max(maxProduct, words[i].count * words[j].count)
203+
}
204+
}
205+
}
206+
207+
return maxProduct
208+
}
209+
}
210+
```
211+
184212
<!-- tabs:end -->
185213

186214
<!-- solution:end -->
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
func maxProduct(_ words: [String]) -> Int {
3+
let n = words.count
4+
var masks = [Int](repeating: 0, count: n)
5+
6+
for i in 0..<n {
7+
for c in words[i] {
8+
masks[i] |= 1 << (c.asciiValue! - Character("a").asciiValue!)
9+
}
10+
}
11+
12+
var maxProduct = 0
13+
for i in 0..<n {
14+
for j in i+1..<n {
15+
if masks[i] & masks[j] == 0 {
16+
maxProduct = max(maxProduct, words[i].count * words[j].count)
17+
}
18+
}
19+
}
20+
21+
return maxProduct
22+
}
23+
}

0 commit comments

Comments
 (0)