随想录算法训练营第五十五天|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。

相关推荐
数模竞赛Paid answer7 小时前
2026年中青杯数学建模A题数学建模论文智能评估系统与多智能体优化方法求解全过程论文及程序
算法·数学建模·中青杯
银-豆豆7 小时前
数据结构与算法-动态规划、回溯与贪心
算法·动态规划
想吃火锅10059 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
hold?fish:palm9 小时前
24 回文链表
数据结构·c++·链表
Nil20810 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣10 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
qeen8713 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
lucas_AI13 小时前
1.2B 小模型赢过 235B 大模型:NaviDC-OCR 把文档解析卷明白了
人工智能·深度学习·算法
冻柠檬飞冰走茶14 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
民乐团扒谱机14 小时前
【微实验】倒谱算法(Cepstrum)深度解析:原理、数学推导与代码实现
人工智能·算法·语音识别