Skip to content

Commit d499e62

Browse files
authored
feat: add swift implementation to lcof2 problem: No.086 (#3471)
1 parent d7c998a commit d499e62

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

lcof2/剑指 Offer II 086. 分割回文子字符串/README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,49 @@ public class Solution {
285285
}
286286
```
287287

288+
#### Swift
289+
290+
```swift
291+
class Solution {
292+
private var n: Int = 0
293+
private var s: String = ""
294+
private var f: [[Bool]] = []
295+
private var t: [String] = []
296+
private var ans: [[String]] = []
297+
298+
func partition(_ s: String) -> [[String]] {
299+
n = s.count
300+
self.s = s
301+
f = Array(repeating: Array(repeating: true, count: n), count: n)
302+
303+
let chars = Array(s)
304+
305+
for i in stride(from: n - 1, through: 0, by: -1) {
306+
for j in i + 1 ..< n {
307+
f[i][j] = chars[i] == chars[j] && f[i + 1][j - 1]
308+
}
309+
}
310+
311+
dfs(0)
312+
return ans
313+
}
314+
315+
private func dfs(_ i: Int) {
316+
if i == n {
317+
ans.append(t)
318+
return
319+
}
320+
for j in i ..< n {
321+
if f[i][j] {
322+
t.append(String(s[s.index(s.startIndex, offsetBy: i)...s.index(s.startIndex, offsetBy: j)]))
323+
dfs(j + 1)
324+
t.removeLast()
325+
}
326+
}
327+
}
328+
}
329+
```
330+
288331
<!-- tabs:end -->
289332

290333
<!-- solution:end -->
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
private var n: Int = 0
3+
private var s: String = ""
4+
private var f: [[Bool]] = []
5+
private var t: [String] = []
6+
private var ans: [[String]] = []
7+
8+
func partition(_ s: String) -> [[String]] {
9+
n = s.count
10+
self.s = s
11+
f = Array(repeating: Array(repeating: true, count: n), count: n)
12+
13+
let chars = Array(s)
14+
15+
for i in stride(from: n - 1, through: 0, by: -1) {
16+
for j in i + 1 ..< n {
17+
f[i][j] = chars[i] == chars[j] && f[i + 1][j - 1]
18+
}
19+
}
20+
21+
dfs(0)
22+
return ans
23+
}
24+
25+
private func dfs(_ i: Int) {
26+
if i == n {
27+
ans.append(t)
28+
return
29+
}
30+
for j in i ..< n {
31+
if f[i][j] {
32+
t.append(String(s[s.index(s.startIndex, offsetBy: i)...s.index(s.startIndex, offsetBy: j)]))
33+
dfs(j + 1)
34+
t.removeLast()
35+
}
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)