Problem: Editing distance refers to changing one string into another, with only 3 operations: Modifying a character, deleting a character, and inserting a character. The change to that: delete E, insert a, insert T. 20 '
Implements the editing distance algorithm.
Solution: Using the idea of dynamic programming, the problem can be decomposed into sub-problems, solving sub-problems so as to get the final answer.
Ideas are as follows:
String S1 and S2
The sub-problem of the editing distance of S1 and S2 is the editing distance of any substring of S1 to any substring of S2 ...
Thus, the editing distance from S1 to S2 can be stored in a matrix of (len1+1) * (len2+1) size
When S1 and S2 are empty, the editing distance (editdistance) is 0;
When there is a null in S1, S2, the length of the edited distance is obviously not empty;
When both S1 and S2 are not empty, editdistance (S1,S2) can be seen as an additional step after the decision in its previous step, where the editing distance from the previous step is mainly from three directions: (S1[1:len1-1], S2), (S1[len1], s2[1:len2-1 ]), (S1[1:len1-1], s2[1:len2-1])
Where (S1[1:len1-1], s2[1:len2-1]) operation is very special, if the current value of the comparison is equal, there is no need to operate, not equal to the operation of +1. therefore editdistance (s1,s2) = min (in the case of ()).
The specific code is as follows: reference: http://blog.csdn.net/yysdsyl/article/details/4249245
intMinintAintBintc) { intt = a<b?a:b; returnT<c?t:c;}voidEditdistance (CharS1[],Chars2[]) { intLen1 =strlen (S1); intLen2 =strlen (S2); int**d =New int*[len1+1]; for(intK =0; k<=len1;k++) D[k]=New int[len2+1]; inti,j; for(i =0; i<=len1;i++) d[i][0] =i; for(j =0; j<=len2;j++) d[0][J] =J; for(i =1; i<=len1;i++) { for(j =1; j<=len2;j++) { intCost = s1[i-1] = = s2[j-1]?0:1; intDeletion = d[i-1][J] +1; intInsertion = d[i][j-1] +1; intsubstitution = d[i-1][j-1] +Cost ; D[I][J]=min (deletion,insertion,substitution); printf ("%3d", D[i][j]); } printf ("\ n"); } printf ("%d\n", D[len1][len2]); for(intK =0; k<=len1;k++) Delete[] d[k]; Delete[] D;}intMainintargcChar*argv[]) {Qcoreapplication A (argc, argv); CharS1[] ="Fxpium"; CharS2[] ="Xwrs"; Editdistance (S1,S2); returna.exec ();}
Written test preparation (2)