随想录算法训练营第五十五天|583.两个字符串的删除操作、72.编辑距离

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

cs 复制代码
public class Solution {
    public int MinDistance(string word1, string word2) {
        char[]w1=word1.ToCharArray();
        char[]w2=word2.ToCharArray();
        int[,]dp=new int[w1.Length+1,w2.Length+1];
        for(int i=1;i<=w1.Length;i++)
        {
            for(int j=1;j<=w2.Length;j++)
            {
                if(w1[i-1]==w2[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-dp[w1.Length,w2.Length]+word2.Length-dp[w1.Length,w2.Length];
    }
}

代码和最长公共子串一个思路,只是最后返回值要处理一下。

72.编辑距离

cs 复制代码
public class Solution {
    public int MinDistance(string word1, string word2) {
        char[]w1=word1.ToCharArray();
        char[]w2=word2.ToCharArray();
        int[,]dp=new int[w1.Length+1,w2.Length+1];
        for(int i=1;i<=w1.Length;i++)
        {
            dp[i,0]=i;
        }
        for(int j=1;j<=w2.Length;j++)
        {
            dp[0,j]=j;
        }
        for(int i=1;i<=w1.Length;i++)
        {
            for(int j=1;j<=w2.Length;j++)
            {
                if(w1[i-1]==w2[j-1])
                {
                    dp[i,j]=dp[i-1,j-1];
                }else
                dp[i,j]=Math.Min(Math.Min(dp[i-1,j-1],dp[i,j-1]),dp[i-1,j])+1;
            }
        }
        return dp[w1.Length,w2.Length];
    }
}

Word1删除一个元素就是Dp[i][j] = Dp[i - 1][j] + 1,Word2删除Dp[i][j] = Dp[i][j - 1] + 1,替换则是Dp[i][j] = dp[i - 1][j - 1] + 1。

相关推荐
多米Domi0113 分钟前
0x3f 第42天 复习 10:39-11:33
算法·leetcode
thubier(段新建)5 分钟前
单招模考试卷模型思考(1)
算法·单招
议题一玩到9 分钟前
#leetcode# 1984. Minimum Difference Between Highest and Lowest of K Scores
数据结构·算法·leetcode
是娇娇公主~9 分钟前
算法——【最长回文子串】
c++·算法
你撅嘴真丑23 分钟前
计算2的N次方 和 大整数的因子
数据结构·c++·算法
孞㐑¥27 分钟前
算法—前缀和
c++·经验分享·笔记·算法
yugi98783842 分钟前
基于MATLAB的延迟求和(DAS)波束形成算法实现
开发语言·算法·matlab
漫随流水1 小时前
leetcode回溯算法(90.子集Ⅱ)
数据结构·算法·leetcode·回溯算法
Yupureki1 小时前
《算法竞赛从入门到国奖》算法基础:搜索-记忆化搜索
c语言·c++·学习·算法·深度优先
June bug1 小时前
(#数组/链表操作)合并两个有重复元素的无序数组,返回无重复的有序结果
数据结构·python·算法·leetcode·面试·跳槽