1. 程式人生 > >DP動態規劃專題九:LeetCode 72. Edit Distance

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];
    }