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

相关推荐
计算机小白一个4 分钟前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^38 分钟前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
大数据追光猿3 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!3 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉3 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生3 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴3 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing3 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财3 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程3 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛