Skip to content

Commit 7bad7f3

Browse files
authored
feat: add swift implementation to lcof2 problem: No.095 (doocs#3481)
1 parent 114b1fb commit 7bad7f3

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lcof2/剑指 Offer II 095. 最长公共子序列/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,30 @@ class Solution {
275275
}
276276
```
277277

278+
#### Swift
279+
280+
```swift
281+
class Solution {
282+
func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int {
283+
let m = text1.count, n = text2.count
284+
let text1Array = Array(text1)
285+
let text2Array = Array(text2)
286+
var f = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)
287+
288+
for i in 1...m {
289+
for j in 1...n {
290+
if text1Array[i - 1] == text2Array[j - 1] {
291+
f[i][j] = f[i - 1][j - 1] + 1
292+
} else {
293+
f[i][j] = max(f[i - 1][j], f[i][j - 1])
294+
}
295+
}
296+
}
297+
return f[m][n]
298+
}
299+
}
300+
```
301+
278302
<!-- tabs:end -->
279303

280304
<!-- solution:end -->
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int {
3+
let m = text1.count, n = text2.count
4+
let text1Array = Array(text1)
5+
let text2Array = Array(text2)
6+
var f = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)
7+
8+
for i in 1...m {
9+
for j in 1...n {
10+
if text1Array[i - 1] == text2Array[j - 1] {
11+
f[i][j] = f[i - 1][j - 1] + 1
12+
} else {
13+
f[i][j] = max(f[i - 1][j], f[i][j - 1])
14+
}
15+
}
16+
}
17+
return f[m][n]
18+
}
19+
}

0 commit comments

Comments
 (0)