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
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size();
int n = word2.size();
vector<vector<int>> f(m+1,vector<int>(n+1,0));
for(int i=0;i<=m;i++)
f[i][0] = i;
for(int j=0;j<=n;j++)
f[0][j] = j;
//f[i][j]前i,j个字符所需要的次数
for(int i=1;i<m+1;i++)
for(int j=1;j<n+1;j++)
{
if(word1[i-1]!=word2[j-1]) //第i个和第j个字符比较
f[i][j] = min(min(f[i-1][j],f[i][j-1]),f[i-1][j-1])+1;
else
f[i][j] = f[i-1][j-1];
}
return f[m][n];
}
};