链接
题目.
难度:
high
解答:
乍一看无从下手,可是我们有万能的动态规划。推导公式就是,当目标字符串增加一个字符的时候需要怎么根据之前的结果得到当前值。完全就是动态规划经典问题:寻找最长公共字符串的翻版
package main
import "fmt"
func minDistance(word1 string, word2 string) int {
if len(word1) == 0 {
return len(word2)
}
if len(word2) == 0 {
return len(word1)
}
dp := make([][]int, len(word1)+1)
for i := 0; i <= len(word1); i++ {
dp[i] = make([]int, len(word2)+1)
}
for i := 1; i <= len(word1); i++ {
dp[i][0] = i
}
for j := 1; j <= len(word2); j++ {
dp[0][j] = j
}
for i := 1; i <= len(word1); i++ {
for j := 1; j <= len(word2); j++ {
//add
dp[i][j] = dp[i][j-1] + 1
//match
if word1[i-1] == word2[j-1] && dp[i-1][j-1] < dp[i][j] {
dp[i][j] = dp[i-1][j-1]
}
//replace
if dp[i-1][j-1]+1 < dp[i][j] {
dp[i][j] = dp[i-1][j-1] + 1
}
//discard
if dp[i-1][j]+1 < dp[i][j] {
dp[i][j] = dp[i-1][j] + 1
}
}
}
//fmt.Println(dp)
return dp[len(word1)][len(word2)]
}
func main() {
fmt.Println(minDistance("horse", "ros"))
}
复杂度分析
time
O(M*n)
space
O(m*n)
执行结果
执行用时 :
0 ms
, 在所有 golang 提交中击败了
100.00%
的用户
内存消耗 :
5.7 MB
, 在所有 golang 提交中击败了
68.75%
的用户
来源:CSDN
作者:Ethan3014
链接:https://blog.csdn.net/weixin_45594127/article/details/103656334