72. Edit Distance

Description

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

Solution

2D-DP, time O(m * n), space O(m * n)

一眼就知道要用DP的题。可以用正向逆向两种思路去做,比较推荐用dp[i][j]来代表word1.substring(0, i)到word2.substring(0, j)的编辑距离,这样子计算距离会方便一些。
注意边界条件的处理,即dp[0][j]和dp[i][0]这种case是需要直接赋值的,避免越界。

class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null || word1.equals(word2)) {
            return 0;
        }
        int m = word1.length();
        int n = word2.length();
        // dp[i][j] means edit distance of word1.substring(0, i) and word2.substring(0, j)
        int[][] dp = new int[m + 1][n + 1];

        for (int i = 0; i <= m; ++i) {
            for (int j = 0; j <= n; ++j) {
                if (i == 0 || j == 0) {
                    dp[i][j] = Math.max(i, j);
                    continue;
                }
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
                }
            }
        }
        
        return dp[m][n];
    }
    
    public int min(int x, int y, int z) {
        return Math.min(x, Math.min(y, z));
    }
}

1D-DP, O(mn), S(n)

由于dp[i + 1]只依赖于dp[i]所以可以将dp数组降维。

class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return -1;
        }
        
        int m = word1.length();
        int n = word2.length();
        int[] dp = new int[n + 1];
        // initialize the first row
        for (int j = 0; j <= n; ++j) {
            dp[j] = j;
        }
        
        for (int i = 1; i <= m; ++i) {
            int prev = dp[0];
            dp[0] = i;

            for (int j = 1; j <= n; ++j) {
                int tmp = dp[j];
                
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[j] = prev;
                } else {
                    dp[j] = 1 + Math.min(Math.min(dp[j], prev), dp[j - 1]);
                }

                prev = tmp;
            }
        }
        
        return dp[n];
    }
}

你可能感兴趣的:(72. Edit Distance)