Topic links
Title Requirements:
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
The analysis of the problem is from a blog post:
The variable we maintain RES[I][J] represents the minimum number of operands that are edited by the first I characters of Word1 and the first J characters of Word2. Assuming we have all the historical information before Res[i][j] to see how to get the current res[i][j in constant time], we discuss two things:
1) If WORD1[I-1]=WORD2[J-1], that is, the current two characters are the same, that is, do not need to edit, it is easy to get res[i][j]=res[i-1][j-1], because the newly added characters do not have to edit;
2) if word1[i-1]!=word2[j-1], then we consider three kinds of operations, if it is inserted word1, then res[i][j]=res[i-1][j]+1, that is, to take word1 i-1 characters and Word2 before the best result of J characters, Then add an insert operation; if you insert Word2, then res[i][j]=res[i][j-1]+1 is the same as the one above; if it is a replace operation, it is similar to the first case above, but a substitution operation is added (because word1[i-1] and word2[ J-1] is not equal, so the recursive type is res[i][j]=res[i-1][j-1]+1. The above list contains all the possibilities, a friend may say why there is no delete operation, in fact, adding an insert operation here will always get the same effect as a delete operation, so the deletion will not make the least number of operands better, so if we are positive thinking, then we do not need to delete the operation. Take the minimum number of operands above, i.e. the result of the second case, res[i][j] = min (Res[i-1][j], res[i][j-1], res[i-1][j-1]) +1.
The program approximate flowchart is as follows:
The procedure is as follows:
1 classSolution {2 Public:3 intMinintAintBintc)4 {5 intTMP = (A < b)?a:b;6 return(TMP < C)?Tmp:c;7 }8 9 intMindistance (stringWord1,stringWord2) {Ten intSzWord1 =word1.size (); One intSzWord2 =word2.size (); A if(SzWord1 = =0) - returnSzWord2; - if(SzWord2 = =0) the returnSzWord1; - -vector<vector<int> > dp (szWord1 +1, vector<int> (SzWord2 +1,0)); - for(inti =0; I < SzWord1 +1; i++) +dp[i][0] =i; - for(intj =0; J < SzWord2 +1; J + +) +dp[0][J] =J; A at for(inti =1; I < SzWord1 +1; i++) - for(intj =1; J < SzWord2 +1; J + +) - { - if(word1[i-1] = = word2[j-1]) -DP[I][J] = dp[i-1][j-1]; - Else inDp[i][j] = min (dp[i-1][J], dp[i][j-1], dp[i-1][j-1]) +1; - } to + returnDp[szword1][szword2]; - } the};
Leetcode's "Dynamic Planning": Edit Distance