Delete Operation for Two Strings

本文介绍了一种利用动态规划求解两字符串转换为相同字符串所需的最少删除操作的方法。通过构建二维数组dp[i][j]表示word1和word2对应子串的操作数,实现了高效的算法解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Delete Operation for Two Strings

A.题意

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: “sea”, “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.

Note:

1.The length of given words won’t exceed 500.
2.Characters in given words can only be lower-case letters.

B.思路

其实这道题跟《算法概论》书上讲的编辑距离的题目差不多了,用动态规划的思维可以解决,我们新建一个二维数组dp[i][j]来表示扫描到word1[i - 1]和word2[j - 1]时对应的操作数,可见此时有三种情况,删去word1[i - 1]与word2的第0到j - 1位对齐,删去word2[j - 1]与word1的0到i - 1位对齐或者此时两个字符对应位置相等不用操作或者此时word1[i - 1]和word2[j - 1]不同而前面的字符串相同要同时删除两者。我们只需要遍历字符串然后取出最小的即可。

C.代码实现

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.size();
        int len2 = word2.size();
        vector<vector<int> > dp(len1 + 1, vector<int>(len2 + 1, 0));
        for (int i = 0;i <= len1;i++)
        {
            dp[i][0] = i;
        }
        for (int i = 0;i <= len2;i++)
        {
            dp[0][i] = i;
        }
        for (int i = 1;i <= len1;i++)
        {
            for (int j = 1;j <= len2;j++)
            {
                int temp = (word1[i - 1] == word2[j - 1]) ? 0 : 2;
                int minnum = min(temp + dp[i - 1][j - 1],1 + dp[i - 1][j]);
                minnum = min(minnum,1 + dp[i][j - 1]);
                dp[i][j] = minnum;
            }
        }
        return dp[len1][len2];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值