【1】【leetcode-72 动态规划】 编辑距离

(没思路,很典型,重要

给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

  1. 插入一个字符
  2. 删除一个字符
  3. 替换一个字符

示例 1:

输入: word1 = "horse", word2 = "ros"
输出: 3
解释: 
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例 2:

输入: word1 = "intention", word2 = "execution"
输出: 5
解释: 
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

关键:

dp[i][j]代表由word1的前i个子串变为word2的前j个子串的花费

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

链接: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()];
    }
}

我:

    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];
    }
原文地址:https://www.cnblogs.com/twoheads/p/10832465.html