Skip to content

Commit 114b1fb

Browse files
authored
feat: add swift implementation to lcof2 problem: No.094 (doocs#3480)
1 parent 7d454bc commit 114b1fb

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

lcof2/剑指 Offer II 094. 最少回文分割/README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,40 @@ public class Solution {
249249
}
250250
```
251251

252+
#### Swift
253+
254+
```swift
255+
class Solution {
256+
func minCut(_ s: String) -> Int {
257+
let n = s.count
258+
let sArray = Array(s)
259+
260+
var g = Array(repeating: Array(repeating: true, count: n), count: n)
261+
262+
for i in stride(from: n - 1, through: 0, by: -1) {
263+
for j in i + 1..<n {
264+
g[i][j] = sArray[i] == sArray[j] && g[i + 1][j - 1]
265+
}
266+
}
267+
268+
var f = Array(repeating: 0, count: n)
269+
for i in 0..<n {
270+
f[i] = i
271+
}
272+
273+
for i in 1..<n {
274+
for j in 0...i {
275+
if g[j][i] {
276+
f[i] = min(f[i], j > 0 ? 1 + f[j - 1] : 0)
277+
}
278+
}
279+
}
280+
281+
return f[n - 1]
282+
}
283+
}
284+
```
285+
252286
<!-- tabs:end -->
253287

254288
<!-- solution:end -->
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
func minCut(_ s: String) -> Int {
3+
let n = s.count
4+
let sArray = Array(s)
5+
6+
var g = Array(repeating: Array(repeating: true, count: n), count: n)
7+
8+
for i in stride(from: n - 1, through: 0, by: -1) {
9+
for j in i + 1..<n {
10+
g[i][j] = sArray[i] == sArray[j] && g[i + 1][j - 1]
11+
}
12+
}
13+
14+
var f = Array(repeating: 0, count: n)
15+
for i in 0..<n {
16+
f[i] = i
17+
}
18+
19+
for i in 1..<n {
20+
for j in 0...i {
21+
if g[j][i] {
22+
f[i] = min(f[i], j > 0 ? 1 + f[j - 1] : 0)
23+
}
24+
}
25+
}
26+
27+
return f[n - 1]
28+
}
29+
}

0 commit comments

Comments
 (0)