This commit is contained in:
krahets
2023-07-19 01:44:39 +08:00
parent ec6f3fd337
commit 1184c791c5
14 changed files with 563 additions and 42 deletions
@@ -213,7 +213,32 @@ $$
=== "Swift"
```swift title="edit_distance.swift"
[class]{}-[func]{editDistanceDP}
/* 编辑距离:动态规划 */
func editDistanceDP(s: String, t: String) -> Int {
let n = s.utf8CString.count
let m = t.utf8CString.count
var dp = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
// 状态转移:首行首列
for i in stride(from: 1, through: n, by: 1) {
dp[i][0] = i
}
for j in stride(from: 1, through: m, by: 1) {
dp[0][j] = j
}
// 状态转移:其余行列
for i in stride(from: 1, through: n, by: 1) {
for j in stride(from: 1, through: m, by: 1) {
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
// 若两字符相等,则直接跳过此两字符
dp[i][j] = dp[i - 1][j - 1]
} else {
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
}
}
}
return dp[n][m]
}
```
=== "Zig"
@@ -458,7 +483,35 @@ $$
=== "Swift"
```swift title="edit_distance.swift"
[class]{}-[func]{editDistanceDPComp}
/* 编辑距离:状态压缩后的动态规划 */
func editDistanceDPComp(s: String, t: String) -> Int {
let n = s.utf8CString.count
let m = t.utf8CString.count
var dp = Array(repeating: 0, count: m + 1)
// 状态转移:首行
for j in stride(from: 1, through: m, by: 1) {
dp[j] = j
}
// 状态转移:其余行
for i in stride(from: 1, through: n, by: 1) {
// 状态转移:首列
var leftup = dp[0] // 暂存 dp[i-1, j-1]
dp[0] = i
// 状态转移:其余列
for j in stride(from: 1, through: m, by: 1) {
let temp = dp[j]
if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
// 若两字符相等,则直接跳过此两字符
dp[j] = leftup
} else {
// 最少编辑步数 = 插入、删除、替换这三种操作的最少编辑步数 + 1
dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1
}
leftup = temp // 更新为下一轮的 dp[i-1, j-1]
}
}
return dp[m]
}
```
=== "Zig"