Given twowords word1 and word2, find the minimum numberof steps required toconvert word1 to word2. (each operation is counted as1 step.)
You have the following 3 operations permitted onaword:a) Insert acharacter
b) Delete acharacter
c) Replace acharacter
这道题目比较简单,在leetcode虽然是hard级别,但是递推关系还是比较容易推出来,
dp[i][j]为数列s1(0,…,i) ->s2(0,…,j)的数列转换的最小距离:
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector<int> t(m+1,2147483647);
vector<vector<int>> dp(n+1,t);
for(int i = 0;i <= n;++i){
dp[i][0] = i;
}
for(int i = 0;i <= m;++i){
dp[0][i] = i;
}
for(int i = 1;i <= n;++i){
for(int j = 1;j <= m;++j){
/*insert a character*/
dp[i][j] = min(dp[i-1][j]+1,dp[i][j]);
/*delete a character*/
dp[i][j] = min(dp[i][j-1]+1,dp[i][j]);
/*repleace a character*/if(word2[i-1] == word1[j-1]){
dp[i][j] = min(dp[i-1][j-1],dp[i][j]);
}else{
dp[i][j] = min(dp[i-1][j-1]+1,dp[i][j]);
}
}
}
return dp[n][m];
}
};