算法训练营Day56(编辑距离)

583. 两个字符串的删除操作

本题和动态规划:115.不同的子序列 相比,其实就是两个字符串都可以删除了,情况虽说复杂一些,但整体思路是不变的。

583. 两个字符串的删除操作 - 力扣(LeetCode)

class Solution {
    public int minDistance(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();
        
        //以i-1为结尾的word1 和以j-1为结尾的word2  相等的最少操作为dp[i][j]
        int [][] dp = new int[len1+1][len2+1];
        for (int i = 0; i < word1.length() + 1; i++) dp[i][0] = i;
        for (int j = 0; j < word2.length() + 1; j++) dp[0][j] = j;
        for(int i = 1;i<=len1;i++){
            for(int j = 1;j<=len2;j++){
                if (word1.charAt(i-1) == word2.charAt(j-1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
                }
            }
        }
        return dp[len1][len2];
    }
}

 72. 编辑距离 

72. 编辑距离 - 力扣(LeetCode)

在上面几道题做完之后,这个还挺简单的

class Solution {
    public int minDistance(String word1, String word2) {
        int len1 = word1.length();
        int len2 = word2.length();

        //以i-1结尾的word1和以j-1为word相等,最少操作次数是dp[i][j]
        int [][] dp = new int[len1+1][len2+1];
        for (int i = 1; i <= len1; i++) {
            dp[i][0] =  i;
         }
        for (int j = 1; j <= len2; j++) {
            dp[0][j] = j;
           }
        for(int i = 1;i<=len1;i++){
            for(int j =1;j<=len2;j++){
                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 - 1]+1, dp[i][j - 1]+1), dp[i - 1][j]+1) ;
                }
            }
        }
        return dp[len1][len2];
    }
}

 编辑距离总结篇   

二刷总结

你可能感兴趣的:(算法)