leetcode 72. 编辑距离

题解

动态规划,dp[i][j] 表示 word1 的前 i 个字母和 word2 的前 j 个字母之间的编辑距离,dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]),特许情况当 word1[i] == word2[j] 时,dp[i][j] = dp[i-1][j-1] 不需要额外操作

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
func minDistance(word1 string, word2 string) int {
m, n := len(word1), len(word2)
dp := make([][]int, m+1)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 0; i <= m; i++ {
dp[i][0] = i
}
for i := 0; i <= n; i++ {
dp[0][i] = i
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if word1[i-1] == word2[j-1] {
dp[i][j] = dp[i-1][j-1]
} else {
dp[i][j] = 1 + min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1]))
}
}
}
return dp[m][n]
}

func min(a, b int) int {
if a < b {
return a
}
return b
}