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 n = word1.length();
int m = word2.length();
if(n == 0)return m;
if(m == 0)return n;
int dp[1000][1000];
int dif = 1;
for(int i = 0; i < n; i++)
{
if(word2[0] == word1[i]) dif = 0;
dp[i][0] = i + dif;
}
dif = 1;
for(int j = 0; j < m; j++)
{
if(word1[0] == word2[j]) dif = 0;
dp[0][j] = j + dif;
}
for(int i = 1; i < n; i++)
{
for(int j = 1; j < m; j++)
{
if(word1[i] == word2[j]) dp[i][j] = dp[i-1][j-1];
else
{
int mi = min(dp[i-1][j],dp[i][j-1]);
mi = min(mi,dp[i-1][j-1]);
dp[i][j] = mi+1;
}
}
}
return dp[n-1][m-1];
}
};