代码随想录训练营Day55:Leetcode583、72

Leetcode583:

问题描述:

给定两个单词 word1word2 ,返回使得 word1word2相同 所需的最小步数

每步可以删除任意一个字符串中的一个字符。

示例 1:

复制代码
输入: word1 = "sea", word2 = "eat"
输出: 2
解释: 第一步将 "sea" 变为 "ea" ,第二步将 "eat "变为 "ea"

示例 2:

复制代码
输入:word1 = "leetcode", word2 = "etco"
输出:4

提示:

  • 1 <= word1.length, word2.length <= 500
  • word1word2 只包含小写英文字母

代码及注释:

cpp 复制代码
class Solution {
public:
    //dp[i][j] :word1 [0,i-1]和word2[0,j-1]的最长公共子序列的长度
    int dp[505][505];
    int minDistance(string word1, string word2) {

        for(int i=1;word1[i-1];i++){
            for(int j=1;word2[j-1];j++){
                if(word1[i-1]==word2[j-1]){
                    dp[i][j]=dp[i-1][j-1]+1;
                }else{
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }

        //找到最长公共子序列之后,将多余的删掉即可
        return word1.size()-dp[word1.size()][word2.size()]+word2.size()-dp[word1.size()][word2.size()];
    }
};

Leetcode72:

问题描述:

给你两个单词 word1word2请返回将 word1 转换成 word2 所使用的最少操作数

你可以对一个单词进行如下三种操作:

  • 插入一个字符
  • 删除一个字符
  • 替换一个字符

示例 1:

复制代码
输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例 2:

复制代码
输入:word1 = "intention", word2 = "execution"
输出:5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

提示:

  • 0 <= word1.length, word2.length <= 500
  • word1word2 由小写英文字母组成

代码及注释:

cpp 复制代码
class Solution {
public:
    // word1 [0,i-1]&& word2 [0,j-1]转换成相同所使用的最少次数
    int dp[505][505];
    int minDistance(string word1, string word2) {

        int n=word1.size();
        int m=word2.size();

        for(int i=0;i<=n;i++)dp[i][0]=i;
        for(int i=0;i<=m;i++)dp[0][i]=i;

        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                //找到每一种操作的情况

                //删除word2的一个字符,相当在word1中插入一个字符
                int a1=dp[i][j-1]+1;
                //删除word1的一个字符,相当在word2中插入一个字符
                int a2=dp[i-1][j]+1;

                //修改word1相当于修改word2
                int a3=dp[i-1][j-1];

                if(word1[i-1]!=word2[j-1])a3+=1;
                //找最小操作次数
                dp[i][j]=min(a1,min(a2,a3));
            }
        }

        return dp[n][m];

        
    }
};
相关推荐
sukalot14 分钟前
windows C++-windows C++-使用任务和 XML HTTP 请求进行连接(二)
c++·windows
_.Switch17 分钟前
Python机器学习模型的部署与维护:版本管理、监控与更新策略
开发语言·人工智能·python·算法·机器学习
qianbo_insist37 分钟前
simple c++ 无锁队列
开发语言·c++
zengy537 分钟前
Effective C++中文版学习记录(三)
数据结构·c++·学习·stl
MinBadGuy1 小时前
【GeekBand】C++设计模式笔记5_Observer_观察者模式
c++·设计模式
自由的dream1 小时前
0-1背包问题
算法
2401_857297912 小时前
招联金融2025校招内推
java·前端·算法·金融·求职招聘
爱上语文2 小时前
Java LeetCode每日一题
java·开发语言·leetcode
良月澪二3 小时前
CSP-S 2021 T1廊桥分配
算法·图论
wangyue44 小时前
c# 线性回归和多项式拟合
算法