题目:
题解:
func minDistance(word1 string, word2 string) int {m, n := len(word1), len(word2)dp := make([][]int, m+1)for i := range dp {dp[i] = make([]int, n+1)}for i := 0; i < m+1; i++ {dp[i][0] = i // word1[i] 变成 word2[0], 删掉 word1[i], 需要 i 部操作}for j := 0; j < n+1; j++ {dp[0][j] = j // word1[0] 变成 word2[j], 插入 word1[j],需要 j 部操作}for i := 1; i < m+1; i++ {for j := 1; j < n+1; j++ {if word1[i-1] == word2[j-1] {dp[i][j] = dp[i-1][j-1]} else { // Min(插入,删除,替换)dp[i][j] = Min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1}}}return dp[m][n]
}
func Min(args ...int) int {min := args[0]for _, item := range args {if item < min {min = item}}return min
}