Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add swift implementation to lcof2 problem: No.086 #3471

Merged
merged 1 commit into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
}
}
}
}
Loading