题目描述
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:
1.Insert a character
2.Delete a character
3.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’)
Example 2:
Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)
分析
这道题的目的是求 word1 转变为 word2 的最少步骤,可以采用动态规划的方法。
对于两个字符串 word1[1…i] 与 word2[1…j] 的匹配,用 E(i,j) 代表现在的情况,其中最右侧的列只有三种情况: word1[i] 对应 空; word2[j] 对应 空;word1[i] 对应 word2[j];则可以将原问题变化为更小的三个子问题进行匹配,并取三个子问题中的最小者
则 E(i,j) = min{1+E(i-1,j), 1+E(i,j-1), diff(i,j)+E(i-1,j-1)} (当word1[i] == word2[j] 令diff(i,j) = 0 ,否则diff(i,j) = 1)
最终结果
class Solution {
public:
int minDistance(string word1, string word2) {
int E[word1.length()+1][word2.length()+1] = {0};
for (int i = 0; i <= word1.length(); i++) {
E[i][0] = i;
}
for (int j = 0; j <= word2.length(); j++) {
E[0][j] = j;
}
for (int i = 1; i <= word1.length(); i++) {
for (int j = 1; j <= word2.length(); j++) {
int tem = 0;
if (word1[i-1] != word2[j-1])
tem = 1;
int min = 1 + E[i-1][j];
int min2 = 1 + E[i][j-1];
int min3 = tem + E[i-1][j-1];
if (min > min2)
min = min2;
if (min > min3)
min = min3;
E[i][j] = min;
}
}
return E[word1.length()][word2.length()];
}
};