DP动态规划专题九:LeetCode 72. Edit Distance

LeetCode 72. Edit Distance

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

Insert a character
Delete a character
Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

解法:由于从word1可以有多种path走到word2,但是题目只要求我们求出最少的操作次数,因此,只是要求出每个node的一个最小值状态,属于动态规划的范畴。假设i是word1的index, j是word2的index,那么从0-i变到0-j需要dp[i][j]次操作,那么我们可以知道dp[0][0] = 0, dp[i][0] = i, dp[o][j] = j, 这就是corner case。接下来我们分析:假设从字符串最后开始向前走,如果charAt(i) == charAt(j),那么dp[i][j] = dp[i-1][j-1]. 如果不相等,那么有三种情况,我们取最小,dp[i][j] = 1 + min {增: dp[i][j-1], 删: dp[i-1][j], 替换: dp[i-1][j-1]}. 因此我们可以写出如下代码:

    public int minDistance(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        int[][] dp = new int[n+1][m+1];
        for (int i = 1; i <= n; i++) dp[i][0] = i;
        for (int i = 1; i <= m; i++) dp[0][i] = i;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (word1.charAt(i-1) == word2.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1];
                } else {
                    dp[i][j] = 1 + Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]);
                }
            }
        }
        return dp[n][m];
    }

由于i,j的状态最远只和i-1,j-1的状态有关,因此,我们可以简化dp二维数组,需要两个一维数组即可。!!!注意!!!:更新pre数组的时候不可以简单的pre = cur; 这样的话只是浅拷贝,之后cur的操作还是在cur本身。需要用temp来做中间值进行交换。这样才达到了交换两个数组空间的作用!!!

    public int minDistance(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();
        int[] pre = new int[m+1];
        int[] cur = new int[m+1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= m; j++) {
                if (i == 0 && j == 0) cur[j] = 0;
                else if (i == 0) cur[j] = j;
                else if (j == 0) cur[j] = i;
                else{
                    if (word1.charAt(i-1) == word2.charAt(j-1)) {
                        cur[j] = pre[j-1];
                    } else {
                        cur[j] = 1 + Math.min(Math.min(cur[j-1], pre[j]), pre[j-1]);
                    }     
                }
            }
            int[] tmp = pre;
            pre = cur;
            cur = tmp;
        }
        return pre[m];
    }

猜你喜欢

转载自blog.csdn.net/katrina95/article/details/85506386