Skip to content

Latest commit

 

History

History
55 lines (50 loc) · 1.44 KB

583.md

File metadata and controls

55 lines (50 loc) · 1.44 KB

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

DP

逆向考虑:总长度-2*最长公共子序列长度。

class Solution {
public:
    int minDistance(string word1, string word2) {
        int size1 = word1.size(), size2 = word2.size();
        int dp[size1+1][size2+1];
        memset(dp, 0, sizeof(dp));
        for (int i = 0; i < size1; i++) {
            for (int j = 0; j < size2; j++) {
                if (word1[i] == word2[j]) {
                    dp[i+1][j+1] = dp[i][j] + 1;
                } else {
                    dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
                }
            }
        }
        return size1+size2-2*dp[size1][size2];
    }
};

正向考虑:dp[i][j]表示s[0:i]与t[0:j]的最小删除次数。

class Solution {
public:
    int minDistance(string word1, string word2) {
        int size1 = word1.size(), size2 = word2.size();
        int dp[size1+1][size2+1];
        memset(dp, 0, sizeof(dp));
        for (int i = 1; i <= size1; i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j <= size2; j++) {
            dp[0][j] = j;
        }
        for (int i = 0; i < size1; i++) {
            for (int j = 0; j < size2; j++) {
                if (word1[i] == word2[j]) {
                    dp[i+1][j+1] = dp[i][j];
                } else {
                    dp[i+1][j+1] = min(dp[i][j+1], dp[i+1][j]) + 1;
                }
            }
        }
        return dp[size1][size2];
    }
};