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:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example

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

Notes:

  1. Double Sequence DP
  2. State: f[i][j] the min edit distance for stringA(0..i) and stringB(0..j)
  3. Function:
    1. f[i][j] = f[i-1][j-1] when A[i-1] == B[j-1]
    2. f[i][j] = min(f[i-1][j-1], f[i-1][j], f[i][j-1])+1
  4. Initialize: f[0][i] = i, f[i][0] = i
  5. Answer: f[m][n]
    public int minDistance(String word1, String word2) {
        if(word1 == null || word2 == null) {
            return -1;
        }

        int m = word1.length();
        int n = word2.length();

        // state
        int[][] f = new int[m+1][n+1];

        // initialize
        for (int i = 0; i <= m; ++i) {
            f[i][0] = i;
        }

        for (int i = 0; i <= n; ++i) {
            f[0][i] = i;
        }

        // function
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (word1.charAt(i-1) != word2.charAt(j-1)) {
                    f[i][j] = Math.min(f[i-1][j-1], Math.min(f[i-1][j], f[i][j-1]))+1;
                } else {
                    f[i][j] = f[i-1][j-1];
                }
            }
        }

        // answer
        return f[m][n];
    }

results matching ""

    No results matching ""