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
首先想到了LCS,但发现忽略了ab,bc这样的测试用例。
正确方法:
如果c!=d,情况稍微复杂一点,
如果在c后面添加一个字d,编辑距离就应该是somestr1c变成somestr2的编辑距离 + 1,也就是d(i,j-1) + 1
如果将c删除了,那就是要将somestr1编辑成somestr2d,距离就是d(i-1,j) + 1
那最后只需要看着三种谁最小,就采用对应的编辑方案了。
class Solution {
public:
/*最优问题,首先选取动态规划和贪心算法。该问题使用动态规划,动态规划列出在做决定的所有选择,找最好的选择*/
int minDistance(string word1, string word2) {
int n1=word1.length(),n2=word2.length();
int maxLen=max(n1,n2);
vector<vector<int>> LCS(n1+1,vector<int>(n2+1,0));
int i,j;
for(int j=0;j<=n2;j++){
LCS[0][j]=j;
}
for(int i=0;i<=n1;i++){
LCS[i][0]=i;
}
for(int i=1;i<=n1;i++){
for(j=1;j<=n2;j++){
if(word1[i-1]==word2[j-1]){
LCS[i][j]=LCS[i-1][j-1];
}
else{
int temp=min(LCS[i-1][j],LCS[i][j-1]);
LCS[i][j]=min(temp,LCS[i-1][j-1])+1;
}
}
}
return LCS[n1][n2];
}
};class Solution {
public:
/*最优问题,首先选取动态规划和贪心算法。该问题使用动态规划,动态规划列出在做决定的所有选择,找最好的选择*/
int minDistance(string word1, string word2) {
int n1=word1.length(),n2=word2.length();
int maxLen=max(n1,n2);
vector<vector<int>> LCS(n1+1,vector<int>(n2+1,0));
int i,j;
for(int j=0;j<=n2;j++){
LCS[0][j]=j;
}
for(int i=0;i<=n1;i++){
LCS[i][0]=i;
}
for(int i=1;i<=n1;i++){
for(j=1;j<=n2;j++){
if(word1[i-1]==word2[j-1]){
LCS[i][j]=LCS[i-1][j-1];
}
else{
int temp=min(LCS[i-1][j],LCS[i][j-1]);
LCS[i][j]=min(temp,LCS[i-1][j-1])+1;
}
}
}
return LCS[n1][n2];
}
};