leetcode 19: Edit Distance
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) { // Start typing your C/C++ solution below // DO NOT write int main() function int n = word1.size(); int m = word2.size(); int d[n+1][m+1]; for( int i=0; i<=n; i++) { d[i][0] = i; } for( int i=0; i<=m; i++) { d[0][i] = i; } for( int i=1; i<=n; i++) { for(int j=1; j<=m; j++) {
//attention: index of d array and word array are different.
d[i][j] = minimum( d[i-1][j] + 1 , d[i][j-1] + 1, d[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1) );
}
}
return d[n][m];
}
int minimum( int x, int y, int z) {
return x>y ? ( y>z ? z : y ) : ( x>z ? z : x );
}
};