Edit Distance
Given two words word1 _and _word2, find the minimum number of operations required to convert word1 _to _word2.
You have the following 3 operations permitted on a word:
Insert a character
Delete a character
Replace a character
Example
Example 1:
Input:
word1 = "horse", word2 = "ros"
Output:
3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')Example 2:
Note
Let's go further and introduce an edit distanceD[i][j]which is an edit distance between the firsticharacters ofword1and the firstjcharacters ofword2.
It turns out that one could computeD[i][j], knowingD[i - 1][j],D[i][j - 1]andD[i - 1][j - 1].
There is just one more character to add into one or both strings and the formula is quite obvious.
If the last character is the same,i.e.word1[i] = word2[j]then
D[i][j]=1+min(D[i−1][j],D[i][j−1],D[i−1][j−1]−1)
and if not, i.e. word1[i] != word2[j]we have to take into account the replacement of the last character during the conversion.
D[i][j]=1+min(D[i−1][j],D[i][j−1],D[i−1][j−1])
So each step of the computation would be done based on the previous computation, as follows:
The obvious base case is an edit distance between the empty string and non-empty string that meansD[i][0] = iandD[0][j] = j.
一句话:相等看对角,不相等取左右对角的最小值+1
Code
Last updated