Skip to content

Commit

Permalink
feat: add swift implementation to lcof2 problem: No.086 (#3471)
Browse files Browse the repository at this point in the history
  • Loading branch information
klever34 committed Sep 2, 2024
1 parent d7c998a commit d499e62
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lcof2/剑指 Offer II 086. 分割回文子字符串/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,49 @@ public class Solution {
}
```

#### Swift

```swift
class Solution {
private var n: Int = 0
private var s: String = ""
private var f: [[Bool]] = []
private var t: [String] = []
private var ans: [[String]] = []

func partition(_ s: String) -> [[String]] {
n = s.count
self.s = s
f = Array(repeating: Array(repeating: true, count: n), count: n)

let chars = Array(s)

for i in stride(from: n - 1, through: 0, by: -1) {
for j in i + 1 ..< n {
f[i][j] = chars[i] == chars[j] && f[i + 1][j - 1]
}
}

dfs(0)
return ans
}

private func dfs(_ i: Int) {
if i == n {
ans.append(t)
return
}
for j in i ..< n {
if f[i][j] {
t.append(String(s[s.index(s.startIndex, offsetBy: i)...s.index(s.startIndex, offsetBy: j)]))
dfs(j + 1)
t.removeLast()
}
}
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
38 changes: 38 additions & 0 deletions lcof2/剑指 Offer II 086. 分割回文子字符串/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution {
private var n: Int = 0
private var s: String = ""
private var f: [[Bool]] = []
private var t: [String] = []
private var ans: [[String]] = []

func partition(_ s: String) -> [[String]] {
n = s.count
self.s = s
f = Array(repeating: Array(repeating: true, count: n), count: n)

let chars = Array(s)

for i in stride(from: n - 1, through: 0, by: -1) {
for j in i + 1 ..< n {
f[i][j] = chars[i] == chars[j] && f[i + 1][j - 1]
}
}

dfs(0)
return ans
}

private func dfs(_ i: Int) {
if i == n {
ans.append(t)
return
}
for j in i ..< n {
if f[i][j] {
t.append(String(s[s.index(s.startIndex, offsetBy: i)...s.index(s.startIndex, offsetBy: j)]))
dfs(j + 1)
t.removeLast()
}
}
}
}

0 comments on commit d499e62

Please sign in to comment.