[leetcode]583. Delete Operation for Two Strings

[leetcode]583. Delete Operation for Two Strings


Analysis

好冷鸭—— [每天刷题并不难0.0]

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.
在这里插入图片描述
求最长相同子串

Implement

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=1; i<=len1; i++){
            for(int j=1; j<=len2; 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 len1-dp[len1][len2]+len2-dp[len1][len2];
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/83862884