Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example 1:
Input: word1 = “horse”, word2 = “ros”
Output: 3
Explanation:
horse -> rorse (replace ‘h’ with ‘r’)
rorse -> rose (remove ‘r’)
rose -> ros (remove ‘e’)
给出字符串单词word1和word2, 问最少经过几步的变换可以把word1变成word2
操作有以下几种:
- 插入一个字符
- 删除一个字符
- 置换一个字符
思路:
dynamic programming
以题目的例子word1 = “horse”, word2 = “ros”
假设i指向word1的字符,j指向word2的字符
假如i指向’h’, j指向’r’
题目说是把word1转换为word2,所以3种操作都在word1进行
当然三种操作进行的前提是当下i和j指向的字符不一致
一致的话直接比较下一个字符
所以
word1[i] == word2[j]时, dp[i][j] = dp[i+1][j+1]
word1[i] != word2[j]时, dp[i][j]取以下3种操作数最少的
1 . 插入
在‘h’前插入’r’,并没有实际插入所以i仍指向的是‘h’,但是默认’r’已经得到了匹配,'r’不再参与比较,所以j走向j+1,所以insert时需要的变换次数是dp[i][j+1] + 1,
*千万不要忘记+1!因为insert本身也是一次操作
2.删除
word1 = “horse”, word2 = “ros”,假如i指向’h’, j指向’r’
删除‘h’即默认’h’不再参与比较,所以i走向i+1
因此delete需要的变换次数是dp[i+1][j] + 1
*千万不要忘记+1!因为delete本身也是一次操作
3.replace
即默认i指向的字符和j指向的字符经过replace后已经一致,所以i和j同时走向下一字符
因此replace需要的变换次数是dp[i+1][j+1] + 1
*千万不要忘记+1!因为replace本身也是一次操作
最后说i和j超出word1和word2边界的情况
i超出边界意味着word1是空字符串,j超过意味着word2是空字符串
word1 = “horse”, word2 = “ros”
假如i=5, j=2, 这时word1=“”, word2=“s“
这时需要变换的次数即插入s,即1步(word2长度-j)
以此类推
public int minDistance(String word1, String word2) {
if (word1.length() == 0) {
return word2.length();
}
if (word2.length() == 0) {
return word1.length();
}
int len1 = word1.length();
int len2 = word2.length();
int[][] dp = new int[len1 + 1][len2 + 1];
for (int i = 0; i < len1; i++) {
dp[i][len2] = len1 - i;
}
for (int i = 0; i < len2; i++) {
dp[len1][i] = len2 - i;
}
for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
if (word1.charAt(i) == word2.charAt(j)) {
dp[i][j] = dp[i + 1][j + 1];
} else {
int insert = dp[i][j + 1];
int delete = dp[i + 1][j];
int replace = dp[i + 1][j + 1];
dp[i][j] = Math.min(insert, Math.min(delete, replace)) + 1;
}
}
}
return dp[0][0];
}