【1】【leetcode-72 動態規劃】 編輯距離

(沒思路,很典型,重要java

給定兩個單詞 word1 和 word2,計算出將 word1 轉換成 word2 所使用的最少操做數 。spa

你能夠對一個單詞進行以下三種操做:code

  1. 插入一個字符
  2. 刪除一個字符
  3. 替換一個字符

示例 1:blog

輸入: word1 = "horse", word2 = "ros"
輸出: 3
解釋: 
horse -> rorse (將 'h' 替換爲 'r')
rorse -> rose (刪除 'r')
rose -> ros (刪除 'e')

示例 2:io

輸入: word1 = "intention", word2 = "execution"
輸出: 5
解釋: 
intention -> inention (刪除 't')
inention -> enention (將 'i' 替換爲 'e')
enention -> exention (將 'n' 替換爲 'x')
exention -> exection (將 'n' 替換爲 'c')
exection -> execution (插入 'u')

 

關鍵:class

dp[i][j]表明由word1的前i個子串變爲word2的前j個子串的花費word

在刪除,插入,修改中取花費最小的那個:dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;di

連接:https://www.nowcoder.com/questionTerminal/81d7738f954242e5ade5e65ec40e5027
來源:牛客網

public class Solution {
    public int minDistance(String word1, String word2) {
        if(word1 == null && word2 == null)
            return 0;
        if(word1 == null)
            return word2.length();
        if(word2 == null)
            return word1.length();
         
        // dp[i][j]表明由word1的前i個子串變爲word2的前j個子串的花費
        // 其中i,j都可爲0,表明空串:""
        int[][] dp = new int[word1.length() + 1][word2.length() + 2];
        dp[0][0] = 0;
        // 首先初始化兩個子串中有一個爲空串的狀況
        for(int i = 1; i <= word1.length(); i++){
            dp[i][0] = i;
        }
        for(int j = 1; j <= word2.length(); j++){
            dp[0][j] = j;
        }
         
        for(int i = 1; i <= word1.length(); i++){
            for(int j = 1; j <= word2.length(); j++){
                // 若是這兩個字符相等,那麼交由上一種狀況處理,如abc,dfc
                // 這種狀況與ab,df花費是同樣的
                // 否則就要在刪除,插入,修改中取花費最小的那個
                if(word1.charAt(i - 1) == word2.charAt(j - 1))
                    dp[i][j] = dp[i-1][j-1];
                else
                    dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
            }
        }
        return dp[word1.length()][word2.length()];
    }
}

 

我:co

    public int minDistance(String word1, String word2) {
        int length1 = word1.length();
        int length2 = word2.length();

        int[][] dp = new int[length1+1][length2+1];
        for (int i=0;i<=length1;i++) {
            dp[i][0] = i;
        }
        for (int i=0;i<=length2;i++) {
            dp[0][i] = i;
        }
        for (int i=1;i<=length1;i++) {
            for (int j=1;j<=length2;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(dp[i-1][j-1],Math.min(dp[i][j-1],dp[i-1][j]));
                }
            }
        }
        return dp[length1][length2];
    }
相關文章
相關標籤/搜索