随想录算法训练营第五十五天|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删除一个元素就是Dpij = Dpi - 1j + 1,Word2删除Dpij = Dpij - 1 + 1,替换则是Dpij = dpi - 1j - 1 + 1。

相关推荐
Rain的Java大神之路8 分钟前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode
NEFU_Jyj14 分钟前
贝尔数(组合数学)
算法
1-1=042 分钟前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
希和20271 小时前
C语言程序设计题|有序数组插入数字冒泡排序
c语言·数据结构·算法
Pniubi1 小时前
力扣73 矩阵置零
算法·leetcode·矩阵
布莱克60511 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH14 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
石小石Orz15 小时前
AI 正在蚕食我们的编码能力
前端·后端·算法
民乐团扒谱机17 小时前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法