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
Solution:
We use f[i][j] to denote the minimum edits to convert the first i element in word1 to become the first j elements in word2.
This state depends on four conditions:
1. remove the last character of the first i characters in word1 and line up with the first j characters in word2.
2. add a character at the end of the first i characters in word1 and line up with the first j characters in word2.
3. replace the character at the end of the first i characters and line up with the first j characters in word2.
4. the last characters of the first i characters in word1 and the first j characters in word2 are the same, no edit needed.
Code:
public class Solution { public int minDistance(String word1, String word2) { int m = word1.length(); int n = word2.length(); int[][] f = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if (i == 0) { f[i][j] = j; continue; } if (j == 0) { f[i][j] = i; continue; } f[i][j] = Math.min(f[i - 1][j] + 1, f[i][j - 1] + 1); f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + 1); if (word1.charAt(i - 1) == word2.charAt(j - 1)) { f[i][j] = Math.min(f[i][j], f[i - 1][j - 1]); } } } return f[m][n]; } }