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
这个就和上课讲到的比较字符串的问题是一样的,书上也有提到,方法就是从右端开始考虑(相当于考虑前缀),分三种情况,对齐(包括匹配与不匹配),第一个字符串为空(insert和delete都相当于空了一个位置),第二个字符为空,比较前缀在这些情况下的最小值,这样就能得到动态规划中的子问题,用E(m,n)来表示第一个string前m位和第二个string前n位的差别数,当m和n分别为字符长度时即为所求,于是得到关系式为:
E(m,n)=min{1+E(m-1,n),1+E(m,n-1),dif(m,n)+E(m-1,n-1)},用二维数组储存答案,即可得到所求。
我的代码:
#include<cmath>
#include<algorithm>
#include<cstdlib>
class Solution {
public:
int minDistance(string word1, string word2) {
int outcome[1000][1000] = {};
for (int i = 0; i <= word1.size(); i++) {
outcome[0][i] = i;
}
for (int i = 0; i <= word2.size(); i++) {
outcome[i][0] = i;
}
for (int i = 1; i <= word2.size(); i++) {
for (int j = 1; j <= word1.size(); j++) {
int s = 1;
if (word1[j-1] == word2[i-1])
s = 0;
int mins = 1 + outcome[i - 1][j];
if (mins > 1 + outcome[i][j - 1]) {
mins = 1 + outcome[i][j - 1];
}
if (mins > s + outcome[i - 1][j - 1]) {
mins = s + outcome[i - 1][j - 1];
}
outcome[i][j] = mins;
}
}
return outcome[word2.size()][word1.size()];
}
};