72. 编辑距离

编辑距离

题目描述:

给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

插入一个字符
删除一个字符
替换一个字符

示例 1:

输入:word1 = “horse”, word2 = “ros”
输出:3
解释:
horse -> rorse (将 ‘h’ 替换为 ‘r’)
rorse -> rose (删除 ‘r’)
rose -> ros (删除 ‘e’)
示例 2:

输入:word1 = “intention”, word2 = “execution”
输出:5
解释:
intention -> inention (删除 ‘t’)
inention -> enention (将 ‘i’ 替换为 ‘e’)
enention -> exention (将 ‘n’ 替换为 ‘x’)
exention -> exection (将 ‘n’ 替换为 ‘c’)
exection -> execution (插入 ‘u’)

提示:

0 <= word1.length, word2.length <= 500
word1 和 word2 由小写英文字母组成

思路:

第一眼 看就是动态规划题,递推公式推导是比较左边+1,上边+1,左上+check(字母是否相同)三个的最小值。

代码:

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)
        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++{
            left := dp[i-1][j] +1
            top := dp[i][j-1] +1
            pre := dp[i-1][j-1]  + check(word1[i-1],word2[j-1])
            dp[i][j] = min(left,min(top, pre))
        }
    }
  
    return dp[m][n]
}

func check(a,b byte)int{
    if a == b{
        return 0
    }
    return 1
}

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

代码效率:

执行用时:4 ms, 在所有 Go 提交中击败了81.82%的用户
内存消耗:5.4 MB, 在所有 Go 提交中击败了94.24%的用户


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!