题目:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
思路:
利用动态规划的思路。dp[i][j]表示word1的前i个字母与word2的前j个字母的编辑距离。我们可以发现如下规律: 1)若word1[i+1]==word2[j+1] dp[i+1][j+1] = dp[i][j];否则,dp[i+1][j+1] = dp[i][j] + 1。(利用替换原则) 2)dp[i+1][j+1]还可以取dp[i][j+1]与dp[i+1][j]中的较小值。(利用删除添加原则) 实际dp[i+1][j+1]应当取上述两种情况的较小值。
代码:
class Solution {
public:
int minDistance(string word1, string word2) {
int ** dp = new int*[word1.size() + 1];
for(int i = 0; i < word1.size() + 1; i++){
dp[i] = new int[word2.size() + 1];
}
for(int i = 0; i < word1.size() + 1; i++){
dp[i][0] = i;
}
for(int i = 1; i < word2.size() + 1; i++){
dp[0][i] = i;
}
for(int i = 0; i < word1.size(); i++){
for(int j = 0; j < word2.size(); j++){
if(word1[i] == word2[j]){
dp[i + 1][j + 1] = dp[i][j];
}
else{
dp[i + 1][j + 1] = dp[i][j] + 1;
if(dp[i][j + 1] + 1 < dp[i + 1][j + 1]){
dp[i + 1][j + 1] = dp[i][j + 1] + 1;
}
if(dp[i + 1][j] + 1 < dp[i + 1][j + 1]){
dp[i + 1][j + 1] = dp[i + 1][j] + 1;
}
}
}
}
return dp[word1.size()][word2.size()];
}
};