编辑距离
题目:
给你两个单词 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')
解题思路:首先从两字符串的最后一个字符开始思考,此时有四种情况:
- 在word1最后插入word2的最后一个字符,此时的编辑次数=word1[0..word1.length-1]转化为word2[0..word2.length-2]的编辑次数+1
- 将word1的最后一个字符替换成word2的最后一个字符,此时的编辑次数=word1[0..word1.length-2]转化为word2[0..word2.length-2]的编辑次数+1
- 将word1的最后一个字符删除,此时的编辑次数=word1[0..word1.length-2]转化为word2[0..word2.length-1]的编辑次数+1
- 当两字符相等时,此时的编辑次数=word1[0..word1.length-2]转化为word2[0..word2.length-2]和上述三种操作中的编辑次数中取最小值
class Solution {
public int minDistance(String word1, String word2) {
int len1 = word1.length(), len2 = word2.length();
char[] ch1 = word1.toCharArray(), ch2 = word2.toCharArray();
// 数组定义:dp[i][j]表示word1[0..i - 1]转化为word2[0..j - 1]的编辑次数
int dp[][] = new int[len1 + 1][len2 + 1];
// 初始化
// dp[i][0] 表示word1[0..i - 1]转化为word2的空串时的编辑次数
for(int i = 1; i <= len1; i++) {
dp[i][0] = i;
}
// 同上
for(int i = 1; i <= len2; i++) {
dp[0][i] = i;
}
/**
状态方程:dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1
**/
for(int i = 1; i <= len1; i++) {
for(int j = 1; j <= len2; j++) {
dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i - 1][j]), dp[i][j - 1]) + 1;
// 两字符相等
if(ch1[i - 1] == ch2[j - 1]) {
dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i][j]);
}
}
}
return dp[len1][len2];
}
}