Title Description:
One way to measure the difference between two strings is to calculate the minimum number of operations required for two string conversions, and the fewer actions required, the more similar the two strings are.
Topic Analysis:
Assume that there are only three types of string operations:
- Insert a character;
- Delete a character;
- Replace one character;
The editing distance between two strings is defined as the minimum number of operations from string str1 to str2. First, the editing distance is not greater than str1.length + str2.length. Assuming the editing distance of the character A and B, consider the following:
- If a[i] = B[j], do you need to do this at this time?
This time the delete and replace operations only make the situation worse, and the insert operation does not make the situation better, so at this point F (i, j) = f (i-1, j-1).
A, from F (i-1, j-1) change, this time only need to a[i] replaced with b[j] can be;
B, from F (i-1, J) Change over, this time only need to a[i] delete;
C, from F (i, j-1) change, this time only need to a[i] after the insertion of the character b[j] can be;
So at this point, f (i, j) = Min{f (I-1,j-1), F (i-1,j), F (i,j-1)} + 1.
Note: where F (i, j) represents the editing distance between a[0..i] and B[0..J].
Program code:
#include <gtest/gtest.h>#include<iostream>#include<string>using namespacestd;intCalcdistance (Const string& A,intOffsetA,Const string& B,intOffsetB) { if(a.size () = =OffsetA) { returnB.size ()-OffsetB; } if(b.size () = =OffsetB) { returnA.size ()-OffsetA; } if(A[offseta] = =B[offsetb]) { returnCalcdistance (A, offseta+1, B, OffsetB +1); } Else { intDist1 = Calcdistance (A, OffsetA, B, OffsetB +1); intDist2 = Calcdistance (A, OffsetA +1, B, OffsetB); intDist3 = Calcdistance (A, OffsetA +1, B, OffsetB +1); intresult = Dist1 < Dist2?Dist1:dist2; Result= Result < Dist3?Result:dist3; returnResult +1; }}intmain_modify () {return 0;} TEST (Bailian, Tlevenshtein) {assert_eq (Calcdistance ("Zero",0,"Ero",0),1); Assert_eq (Calcdistance ("Zero",0,"Fero",0),1); Assert_eq (Calcdistance ("ABCDDEFG",0,"ABCEFG",0),2); Assert_eq (Calcdistance ("ABCDDEFG",0,"ABCDDEFG",0),0); Assert_eq (Calcdistance ("ABCDDFG",0,"ABCDDEFG",0),1); Assert_eq (Calcdistance ("",0,"",0),0); Assert_eq (Calcdistance ("ABCDEFGH",0,"",0),8); Assert_eq (Calcdistance ("",0,"ABCDEFGH",0),8);}
reference :
Http://www.cnblogs.com/tianchi/archive/2013/02/25/2886964.html
[Classic algorithm] string similarity-Edit distance