Given 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
Ideas:
A typical dynamic programming problem, recursion to time out oh. State transition equation:
A[i][j] = min (
1. A[i-1][j] + 1,
2. a[i][j-1] + 1,
3. word1[i] = = Word2[j]? A[I-1][J-1]: a[i-1][j-1] + 1
);
C++:
1 classSolution {2 Public:3 intMindistance (stringWord1,stringWord2) {4 5 Const introw = Word1.size () +1;6 Const intcol = word2.size () +1;7 8 intA[row][col];9 Ten for(inti =0; i < row; i++) Onea[i][0] =i; A for(inti =0; I < col; i++) -a[0][i] =i; - the for(inti =1; i < row; i++) - for(intj =1; J < Col; J + +) -A[i][j] = min (word1[i-1] = = word2[j-1] ? a[i-1][j-1]: (a[i-1][j-1] +1)), Min (a[i-1][J] +1, a[i][j-1] +1)); - + returna[row-1][col-1]; - } +};
"Leetcode 72" Edit Distance