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
If we're going to turn the string str1 into str2,
SSTR1 (i) is a substring of str1, range [0 to I], SSTR1 (0) is an empty string
SSTR2 (j) is a substring of str2, ibid.
D (i,j) indicates the editing distance of sstr1 (i) into SSTR2 (j)
First d (0,t), 0<=t<=str1.size () and D (k,0) are very obvious.
When we are calculating D (i,j), we calculate the editing distance between SSTR1 (i) and Sstr2 (j),
At this time, set SSTR1 (i) Form is somestr1c;sstr2 (i) shape such as somestr2d,
The editing distance that turns somestr1 into SOMESTR2 is known as D (i-1,j-1)
The editing distance that turns somestr1c into SOMESTR2 is known as D (i,j-1)
The editing distance that turns somestr1 into somestr2d is known as D (I-1,J)
Then using these three variables, you can hand out D (i,j):
If C==d, obviously the editing distance and D (i-1,j-1) are the same
If C!=d, the situation is slightly more complicated,
- If C is replaced by D, the editing distance is somestr1 to Somestr2 's edit distance + 1, which is D (i-1,j-1) + 1
- If you add a word D after C, the editing distance should be somestr1c to SOMESTR2 's edit distance + 1, which is D (i,j-1) + 1
- If C is deleted, it is to edit the somestr1 into somestr2d, the distance is D (i-1,j) + 1
That last only needs to look at three kinds of who is the smallest, to adopt the corresponding editing scheme.
The above analysis of the algorithm comes from the blog Unieagle
In the following implementation code, I use a scrolling array instead of a two-dimensional array. And only one array is assigned.
In addition, the variable dist_i1_j1 represents D (I-1, j-1)
Dist_i_j means D (i,j)
Dist_i1_j means D (i-1, J)
Dist_i_j1 means D (i, j-1)
In addition, the following code, in fact, the variable
can be dispensed with.
But keep it, you can be more intuitive.
The actual execution time on the Leetcode is 28ms.
Class Solution {public: int mindistance (string word1, String word2) { if (word1.size () < Word2.size ()) Word1.swap (WORD2); if (!word2.size ()) return word1.size (); Vector<int> Dist (word2.size ()); for (int j=0; j<dist.size (); j + +) dist[j] = j+1; for (int i=0; i<word1.size (); i++) { int dist_i1_j1 = i; int dist_i_j1 = dist_i1_j1 +1; for (int j=0; j<word2.size (); j + +) { const int dist_i1_j = Dist[j]; const int Dist_i_j = Word1[i] = = Word2[j]? Dist_i1_j1:min (min (dist_i1_j1, Dist_i1_j), dist_i_j1) + 1; dist_i_j1 = Dist_i_j; Dist_i1_j1 = Dist[j]; DIST[J] = Dist_i_j; } } return Dist.back (); }};
Edit Distance--Leetcode