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

题目描述

给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。

示例 1:

输入: “sea”, “eat”
输出: 2
解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"

解答

本题本质上是求最长公共子序列。求出最长公共子序列的长度既可以得到答案。
r e s u l t = w o r d 1. s i z e ( ) + w o r d 2. s i z e ( ) − 2 ∗ m a x _ l e n _ o f _ s u b s e q u e n c e result = word1.size() + word2.size() - 2*max\_len\_of\_subsequence result=word1.size()+word2.size()2max_len_of_subsequence
最长公共子序列问题求解方法:https://blog.csdn.net/yuanliang861/article/details/89371578

class Solution {
public:
    int minDistance(string word1, string word2) {
        int n=word1.size(), m=word2.size();
        vector<vector<int>> dp(n+1,vector<int>(m+1,0));
        for(int i=1;i<n+1;++i)
        {
            for(int j=1;j<m+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 m+n-2*dp[n][m];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值