iven 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
lev(0,0)=0
lev(i,0)=i
lev(0,j)=j
这道题目的关键在于递归表达式的推导,这是很关键的,如何推导出编辑距离?
递归表达式
class Solution {
public:
int minDistance(string word1, string word2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int row = word1.length() + 1;
int col = word2.length() + 1;
vector<vector<int> > f(row, vector<int>(col));
for (int i = 0; i < row; i++)
f[i][0] = i;
for (int i = 0; i < col; i++)
f[0][i] = i;
for (int i = 1; i < row; i++)
for (int j = 1; j < col; j++){
if (word1[i-1] == word2[j-1])
f[i][j] = f[i-1][j-1];
else
f[i][j] = f[i-1][j-1] + 1;
f[i][j] = min(f[i][j], min(f[i-1][j]+1, f[i][j-1]+1));
}
return f[row-1][col-1];
}
};
如果你对编辑距离还是不太理解的话,可以这么去思考这个问题,首先,你通过一些一般的操作应该能得到这个结论:手动求解编辑距离的话,我应该尽量把那些公共子序列中最长的保留下来,其他的通过增删改的方法进行变化,这样得到的编辑距离才是最小的。于是这个编辑距离就可以转换成求解公共最长子序列LCS的问题,LCS表示最长公共子序列,denstr表示目标串。举个例子:
abce 目的串 acd,首先对其
(a b c) e
(a c) d,然后就可以看出编辑距离为2