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.096 #3482

Merged
merged 1 commit into from
Sep 3, 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
45 changes: 45 additions & 0 deletions lcof2/剑指 Offer II 096. 字符串交织/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,51 @@ public class Solution {
}
```

#### Swift

```swift
class Solution {
private var memo = [String: Bool]()
private var s1: [Character] = []
private var s2: [Character] = []
private var s3: [Character] = []
private var m = 0
private var n = 0

func isInterleave(_ s1: String, _ s2: String, _ s3: String) -> Bool {
m = s1.count
n = s2.count
if m + n != s3.count {
return false
}
self.s1 = Array(s1)
self.s2 = Array(s2)
self.s3 = Array(s3)
return dfs(0, 0)
}

private func dfs(_ i: Int, _ j: Int) -> Bool {
if i >= m && j >= n {
return true
}
let key = "\(i),\(j)"
if let cached = memo[key] {
return cached
}
let k = i + j
var ans = false
if i < m && s1[i] == s3[k] && dfs(i + 1, j) {
ans = true
}
if !ans && j < n && s2[j] == s3[k] && dfs(i, j + 1) {
ans = true
}
memo[key] = ans
return ans
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
40 changes: 40 additions & 0 deletions lcof2/剑指 Offer II 096. 字符串交织/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
class Solution {
private var memo = [String: Bool]()
private var s1: [Character] = []
private var s2: [Character] = []
private var s3: [Character] = []
private var m = 0
private var n = 0

func isInterleave(_ s1: String, _ s2: String, _ s3: String) -> Bool {
m = s1.count
n = s2.count
if m + n != s3.count {
return false
}
self.s1 = Array(s1)
self.s2 = Array(s2)
self.s3 = Array(s3)
return dfs(0, 0)
}

private func dfs(_ i: Int, _ j: Int) -> Bool {
if i >= m && j >= n {
return true
}
let key = "\(i),\(j)"
if let cached = memo[key] {
return cached
}
let k = i + j
var ans = false
if i < m && s1[i] == s3[k] && dfs(i + 1, j) {
ans = true
}
if !ans && j < n && s2[j] == s3[k] && dfs(i, j + 1) {
ans = true
}
memo[key] = ans
return ans
}
}
Loading