Edit Distance
Given two string word1 and word2, return the minimum number of operation required to converted word1 to word2.
Following three operations are permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example:
1 | Input: word1 = "horse", word2 = "ros"; |
Constraints:
- 0 <= len(word1), len(word2) <= 500
- word1 and word2 consist of lower case English letters
Solution
1 | class EditDistance { |
Explanation:
Use matrix[i][j] to represents the edit distance between string word1[0…i] and word2[0…j]. The index of string’s content begins at 1, matrix[0][0] indicates the case that word1 and word2 are both vacant, which means their edit distance is 0. So, it is obvious that matrix[0][j] is the case when word1 is empty and the length of word2 is j, and their edit distance should be just j. Similarly, matrix[0][i] is the case when the length of word1 is i and word2 is empty, their edit distance is i.
Then we can deduce the equation for the above three operations accordingly:
- matrix[i - 1][j] + 1: insert the last character of word1 into the tail of word2
- matrix[i][j - 1] + 1: delete the last character of word2
- matrix[i - 1][j - 1] + 1: replace the last character of word2 by the last character of word1