动态规划
f[i][j]
记录 word1[1..i]
到 word2[1..j]
的最短编辑距离。则考虑三种情况:
- word1插入一个字符和word2相等:
f[i][j-1] + 1
- word1删除一个字符和word2相等:
f[i-1][j] + 1
- word1替换一个字符和word2相等:
f[i-1]f[j-1] + eq
。其中eq考虑两种状态,如果word1要替换的这个字符和word2的最后一个字符相等,则表示不需要替换已经相等,eq等0,否则eq等于1
时间复杂度: O(MN)
空间复杂度: O(MN)
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 31 32 33 34 35 36 37 38 39 40 41 42 43
| func minDistance(word1 string, word2 string) int {
m := len(word1) n := len(word2) f := make([][]int, m+1)
for i := 0; i <= m; i++ { f[i] = make([]int, n+1) for j := 0; j <= n; j ++ { if i == 0 { f[i][j] = j continue }
if j == 0 { f[i][j] = i continue }
temp := min(f[i][j-1] + 1, f[i-1][j] + 1)
eq := 1 if word1[i-1] == word2[j-1] { eq = 0 } temp = min(temp, f[i-1][j-1]+eq)
f[i][j] = temp } }
return f[m][n] }
func min(a, b int) int { if a > b { return b } return a }
|