Edit distance total accepted: 14997 total submissions: 59129my submissions
Given two 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
Question: If you have two words, you can add, delete, or replace one character. How many operations do you need to perform to change the first word to the second one?
Idea: DP
F [I] [J] indicates the minimum editing distance from word1 [1. J] To word2 [1. I ].
If word2 [I] = word1 [J], F [I] [J] = f [I-1] [J-1]
Else f [I] [J] = min {f [I-1] [J-1], F [I] [J-1], f [I-1] [J]} + 1
Complexity: time O (N), Space O (1)
Int mindistance (string word1, string word2) {If (word1.empty () return word2.size (); If (word2.empty () return word1.size (); vector <vector <int> dp (word1.size () + 1, vector <int> (word2.size () + 1, 0 )); /// initialize for (INT I = 0; I <= word1.size (); ++ I) DP [I] [0] = I; for (Int J = 0; j <= word2.size (); ++ J) DP [0] [J] = J; // Iteration for (INT I = 0; I <word1.size (); ++ I) {for (Int J = 0; j <word2.size (); ++ J) {int II = I + 1, JJ = J + 1; if (word1 [I] = word2 [J]) DP [II] [JJ] = DP [II-1] [JJ-1]; else DP [II] [JJ] = min (DP [II] [JJ-1], DP [II-1] [JJ]), DP [II-1] [JJ-1]) + 1 ;}} return DP [word1.size ()] [word2.size ()];}
Leetcode DP edit distance