0072.编辑距离
方法一:动态规划
时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。
func min(a, b int) int {
if a < b {
return a
}
return b
}
func minDistance(word1 string, word2 string) int {
dp, m, n := make([][]int, len(word1)+1), len(word1), len(word2)
for i := 0; i <= m; i++ {
dp[i] = make([]int, n+1)
}
for i := 1; i <= m; i++ {
dp[i][0] = i
}
for i := 1; i <= n; i++ {
dp[0][i] = i
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if word1[i] == word2[j] {
dp[i+1][j+1] = dp[i][j]
} else {
dp[i+1][j+1] = min(dp[i][j+1], min(dp[i][j], dp[i+1][j])) + 1
}
}
}
return dp[m][n]
}