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:

  • Insert a character
  • Delete a character
  • Replace a character
Example

Given word1 = "mart" and word2 = "karma", return 3.

Solution: Dynamic Programming

f[i][j] = MIN(f[i-1][j-1], f[i-1][j]+1, f[i][j-1]+1) // a[i] == b[j]

= MIN(f[i-1][j], f[i][j-1], f[i-1][j-1]) + 1 // a[i] != b[j]

intialize: f[i][0] = i, f[0][j] = j

answer: f[a.length()][b.length()]

public int minDistance(String word1, String word2) {
    if (word1 == null || word2 == null) {
        return -1;
    }
    //minDistance[i][j] = minimum distance to convert first i chars of word 1
    //to first j chars of word 2
    int[][] minDistance = new int[word1.length() + 1][word2.length() + 1];
    //init the first column -- word2 is empty
    for (int i = 0; i < minDistance.length; i++) {
        minDistance[i][0] = i;
    }
    //init the first row -- word1 is empty
    for (int j = 0; j < minDistance[0].length; j++) {
        minDistance[0][j] = j;
    }

    for (int i = 1; i <= word1.length(); i++) {
        for (int j = 1; j <= word2.length(); j++) {
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                minDistance[i][j] = Math.min(Math.min(minDistance[i - 1][j - 1],
                                minDistance[i - 1][j] + 1), minDistance[i][j - 1] + 1);
            } else {
                minDistance[i][j] = Math.min(Math.min(minDistance[i - 1][j - 1],
                                minDistance[i - 1][j]), minDistance[i][j - 1]) + 1;
            }
        }
    }
    return minDistance[word1.length()][word2.length()];
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *