72.编辑距离

72. 编辑距离

难度困难2145

给你两个单词 word1word2请返回将 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
  • word1word2 由小写英文字母组成

思路:
构建dp数组
dp[row][0]=row;
dp[0][column]=column;
考虑四种情况
1.dp[row][column]=dp[row-1][column]+1
2.dp[row][column]=dp[row][column-1]+1
3.最后一个字母不同的情况下,dp[row][column]=dp[row-1][column-1]+1
4.最后一个字母相同的情况下,dp[row][column]=dp[row-1][column-1]

四种情况下最小值就是值

代码:
class Solution {
public int minDistance(String word1, String word2) {
if(word1 == null || word2 == null)return 0;
char[] cs1 = word1.toCharArray();
char[] cs2 = word2.toCharArray();
int[][] dp = new int[cs1.length+1][cs2.length+1];
dp[0][0] = 0;
//第0行
for (int i=1;i<=cs1.length; i++) {
dp[i][0]=i;
}
//第0列
for (int j=1;j<=cs2.length; j++) {
dp[0][j]=j;
}
//其他
for (int i=1;i<=cs1.length; i++) {
for (int j=1;j<=cs2.length; j++) {
int top = dp[i-1][j]+1;
int left = dp[i][j-1]+1;
int topLeft = dp[i-1][j-1];
if(cs1[i-1]!=cs2[j-1]){
topLeft=topLeft+1;
}
dp[i][j]=Math.min(Math.min(top,left),topLeft);

        }           
    }
    return dp[cs1.length][cs2.length];
}

}

你可能感兴趣的:(72.编辑距离)