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
Code;
<span style="font-size:14px;">class Solution {
public:
int minDistance(string word1, string word2) {
int length1 = word1.size(), length2 = word2.size();
int **dp = new int *[length1+1];
for (int i = 0; i < length1+1; i++)
dp[i] = new int[length2+1];
dp[0][0] = 0;
for (int i = 1; i < length1+1; i++)
dp[i][0] = i;
for (int i = 1; i < length2+1; i++)
dp[0][i] = i;
for (int i = 1; i < length1+1; i++)
for (int j = 1; j < length2+1; j++)
if (word1[i-1] == word2[j-1]) {
dp[i][j] = min(dp[i][j-1]+1, dp[i-1][j]+1);
dp[i][j] = min(dp[i-1][j-1], dp[i][j]);
} else {
dp[i][j] = min(dp[i][j-1]+1, dp[i-1][j]+1);
dp[i][j] = min(dp[i-1][j-1]+1, dp[i][j]);
}
int result = dp[length1][length2];
for (int i = 0; i < length1+1; i++)
delete [] dp[i];
delete [] dp;
return result;
}
};</span>