[LeetCode] 72. Edit Distance
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
b) Delete a character
c) Replace a character
Thought process:
- Sub-problem: find the edit distance between word1[0, i] and word2[0, j].
- Function:
- If word1[i] == word2[j], we can be greedy and f[i][j] = f[i - 1][j - 1].
- Else, f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1
- Initialization: f[i][0] = i and f[0][i] = i because any word's edit distance with an empty word is the length of the word.
- Answer: the answer is at f[word1.length][word2.length].
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Solution { public int minDistance(String word1, String word2) { int length1 = word1.length(); int length2 = word2.length(); int[][] f = new int[length1 + 1][length2 + 1]; for (int i = 0; i <= length1; i++) { f[i][0] = i; } for (int i = 1; i <= length2; i++) { f[0][i] = i; } for (int i = 1; i <= length1; i++) { for (int j = 1; j <= length2; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { f[i][j] = f[i - 1][j - 1]; } else { f[i][j] = Math.min(f[i - 1][j - 1], Math.min(f[i - 1][j], f[i][j - 1])) + 1; } } } return f[length1][length2]; } } |
Time complexity:
Say the lengths of word1 and word2 are a and b. The time complexity is O(ab).
Comments
Post a Comment