Leetcode 583. 两个字符串的删除操作 动态规划

/*
 * @lc app=leetcode.cn id=583 lang=cpp
 *
 * [583] 两个字符串的删除操作
 *
 * https://leetcode-cn.com/problems/delete-operation-for-two-strings/description/
 *
 * algorithms
 * Medium (54.63%)
 * Likes:    184
 * Dislikes: 0
 * Total Accepted:    17.9K
 * Total Submissions: 32.8K
 * Testcase Example:  '"sea"
"eat"'
 *
 * 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
 * 
 * 
 * 
 * 示例:
 * 
 * 输入: "sea", "eat"
 * 输出: 2
 * 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
 * 
 * 
 * 
 * 
 * 提示:
 * 
 * 
 * 给定单词的长度不超过500。
 * 给定单词中的字符只含有小写字母。
 * 
 * 
 */

思路:

labuladong讲解

先计算两个字符串的最大公共子序列lcs,然后m-lcs+n-lcs就是word1和word2需要删除的字符数

我的LCS

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m=word1.size();
        int n=word2.size();
        vector<vector<int>> dp(m+1,vector<int>(n+1,0));
        for(int i=1;i<=m;++i){
            for(int j=1;j<=n;++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]);
            }
        }
        int lcs=dp[m][n];
        return m-lcs+n-lcs;
    }
};
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
原文地址:https://www.cnblogs.com/zl1991/p/14714851.html