Problem:
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
Hide TagsDynamic Programming StringTest instructions: Word1 the minimum number of steps required to convert a string to Word2, including inserting, replacing, and deleting one character
Thinking:
(1) Seeking global optimal solution, locking DP Method
(2) DP State transfer formula is not easy to find, there are a few are DP method Common, can be a little inspiration: 1, DP mostly with the use of the array to implement the recursive operation 2, the time complexity of DP method: one-dimensional O (N), two-dimensional: O (m*n)
(3)
If we use I to represent the subscript of the current string A, J represents the subscript of the current string B. If we use D[i, J] to represent the minimum number of edit operations between a[1, ..., i] b[1, ..., j]. Then we will have the following findings:
1. d[0, j] = J;
2. d[i, 0] = i;
3. D[i, J] = D[i-1, j-1] if a[i] = = B[j]
4. D[i, J] = min (d[i-1, j-1], D[i, j-1], D[i-1, J]) + 1 if a[i]! = B[j]//represent replace, INSERT, delete, respectively
Code
Class Solution {public: int mindistance (string word1, String word2) { vector<vector<int> > F ( Word1.size () +1, vector<int> (Word2.size () +1)); F[0][0] = 0; for (int i = 1; I <= word2.size (); i++) f[0][i] = i; for (int i = 1; I <= word1.size (); i++) f[i][0] = i; for (int i = 1; I <= word1.size (), i++) for (int j = 1; J <= Word2.size (); j + +) { F[i][j] = int_max;
if (word1[i-1] = = word2[j-1]) f[i][j] = f[i-1][j-1]; F[i][j] = min (F[i][j], f[i-1][j-1] + 1); Replace f[i][j] = min (f[i][j], min (F[i-1][j], f[i][j-1]) + 1);//delete or insert } return f[word1.size ()][word2.size ()];} ;
Leetcode | | 72. Edit Distance