题目
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
思路
编辑距离是指一个字符串变换为另一个字符串所需最小编辑操作——包括插入,删除以及字符替换的次数。
寻找两个字符串x[1…m]与y[1…n]之间的编辑距离,利用动态规划来解决这个问题,用子问题E(i,j)来表示两个字符串前缀x[1…i]与y[1…j]的编辑距离,这样最终目标就是计算E(m,n)。
对于子问题E(i,j)来说,有三种情况:
如上图中所示,
第一种情况是x[i]对应于一个空隙(插入或删除操作),需要的代价是1,即这一步编辑距离为1,前提是子问题E(i-1,j);
类似的第二种情况y[i]对应于一个空隙,编辑距离为1,前提是子问题E(i,j-1);
第三种情况中,x[i]对应于y[j]:当x[i]==y[j]时,不需要操作,编辑距离是0;当x[i]!=y[j]时,需要字符替换,编辑距离是1,前提是子问题E(i-1,j-1)
对于E(i,j)来说就是从上面三种情况中选出编辑距离最小的情况,由此可以得到子问题E(i,j)的方程:
E(i,j)=min{1+E(i-1,j),1+E(i,j-1),diff(x[i],y[j])+E(i-1,j-1)}
其中当x[i]==y[j]时,diff(x[i],y[j])=0;当x[i]!=y[j]时,diff(x[i],y[j])=1
其中,最小子问题,i和j分别为0时的情况,很容易看出,
E(i,0)=i,E(0,j)=j
这样就可以得到E(i,j)的二维矩阵,返回E(m,n)就是最终的结果。
代码
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
if(m==0&&n==0)
return 0;
vector<vector<int> > E(m + 1, vector<int> (n + 1, 0));
for(int i = 0;i<=m;i++)
{
E[i][0] = i;
}
for(int j = 1;j <= n; j++)
{
E[0][j] = j;
}
for(int i = 1;i <= m;i++)
{
for(int j = 1;j<=n;j++)
{
if(word1[i-1]==word2[j-1]) //此处需要注意下标
E[i][j] = min( E[i-1][j-1], min( 1+E[i-1][j], 1+E[i][j-1]));
else
E[i][j] = min(1+E[i-1][j-1],min(1+E[i-1][j], 1+E[i][j-1]));
}
}
return E[m][n];
}
};