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

动态规划

class Solution {
    public int minDistance(String word1, String word2) {

        /**
         * dp[i][j]定义为以word1[i - 1]结尾的字符串,和以word2[j - 1]结尾的字符串,要想相等需要删除的最小元素个数
         * 当一个为空时,就只能删除另一个字符串中的所有元素
         */
        int[][] dp = new int[word1.length() + 1][word2.length() + 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 < word1.length() + 1; i++) {

            for (int j = 1; j < word2.length() + 1; j++) {

                if (word1.charAt(i - 1) == word2.charAt(j - 1)){
                    dp[i][j] = dp[i - 1][j - 1];
                }

                /**
                 * 如果不匹配,有三种删除的操作
                 * 1、只删除word1[i - 1]
                 * 2、只删除word2[j - 1]
                 * 3、同时删除word1[i - 1]和word2[j - 1]
                 */
                else {
                    dp[i][j] = Math.min(dp[i - 1][j] + 1, Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + 2));
                }
            }
        }

        return dp[word1.length()][word2.length()];
    }
}

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O(n^2)
 */

《1143. 最长公共子序列》改编

class Solution {
    public int minDistance(String word1, String word2) {

        /**
         * 先求出最长公共子串,然后用word1和word2的总长度减去两倍公共长度,就是二者删除的元素个数
         */
        int[][] dp = new int[word1.length() + 1][word2.length() + 1];

        for (int i = 1; i < word1.length() + 1; i++) {

            for (int j = 1; j < word2.length() + 1; j++) {

                if (word1.charAt(i - 1) == word2.charAt(j - 1)){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        
        return word1.length() + word2.length() - 2 * dp[word1.length()][word2.length()];
    }
}

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O(n^2)
 */

https://leetcode-cn.com/problems/delete-operation-for-two-strings/

posted @   振袖秋枫问红叶  阅读(54)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示