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
给定两个字符串word1,word2,要求把word1转换成word2的最小编辑距离(这里距离指编辑的次数,修改,插入,删除都各算一步)
用动态规划来解,定义一个二维向量d[i][j]保存word1中的前i个字符转换成word2的前j个字符所需的最小编辑次数(d[0][3]表示word 1是0个字符,转换成word2前3个字符,显然是3;d[4][2]表示word1前4个字符转换成word2前2个字符所需的编辑次数…)
当word1的第i个字符(word1[i-1])与word2的第j个字符(word2[j-1])相等时,此时d[i][j]=d[i-1][j-1]
如果word1[i-1] != word2[j-1]
1 通过替换操作把word[i-1]替换成word[j-1],那么
d[i][j] = d[i-1][j-1] + 1;
2 通过插入操作在word1后面插入word2[j-1], 那么就相当于计算
d[i][j] = d[i][j-1] + 1;
3 通过插入操作在word2后面插入word1[i-1],那么就是
dis[i][j] = d[i-1][j] + 1;
这种类型的题目好像只能用动态规划,不知道还能用什么方法
class Solution {
public:
int minDistance(string word1, string word2) {
int len1=word1.size();
int len2=word2.size();
vector<vector<int>> d(len1+1,vector<int>(len2+1));//二维向量d要记录word1,word2的所有字符修改的次数,最后一个下标为d[len1][len2],所以向量的长度要加1(没加的话,会出现runtime error)
d[0][0]=0;
for(int i=1;i<=len1;i++)d[i][0]=i;
for(int j=1;j<=len2;j++)d[0][j]=j;
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(word1[i-1]==word2[j-1])
d[i][j]=d[i-1][j-1];
else
d[i][j]=min(d[i-1][j-1],min(d[i-1][j],d[i][j-1]))+1;
}
}
return d[len1][len2];
}
};