代码随想录算法训练营第56天| 583. 两个字符串的删除操作 72. 编辑距离

  • 今日学习的文章链接,或者视频链接

第九章 动态规划part16

  • 自己看到题目的第一想法

  • 看完代码随想录之后的想法

583

方法一:通过计算LCS:

class Solution {
public:
    int longestCommonSubsequence(string word1, string word2){
        int m = word1.size();
        int n = word2.size();
        vector> dp(m+1,vector(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] = 1+dp[i-1][j-1];
                }else{
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        return dp[m][n];
    }
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        int lcs = longestCommonSubsequence(word1,word2);
        return m+n-lcs-lcs;
    }
};

方法二:直接dp

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        vector> dp(m+1,vector(n+1,0));
        for (int i = 0;i<=m;i++){
            dp[i][0] = i;
        }
        for(int j = 0;j<=n;j++){
            dp[0][j] = j;
        }
        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];
                }else{
                    dp[i][j] = min(dp[i-1][j]+1,min(dp[i][j-1]+1,dp[i-1][j-1]+2));
                }
            }
        }
        return dp[m][n];
    }
};

72

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        vector> dp(m+1,vector(n+1,0));
        for(int i = 0;i<=m;i++){
            dp[i][0] = i;
        }
        for(int j = 0;j<=n;j++){
            dp[0][j] = j;
        }
        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];
                }else{
                    dp[i][j] = min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;
                }
            }
        }
        return dp[m][n];
    }
};

  • 自己实现过程中遇到哪些困难

  • 今日收获,记录一下自己的学习时长

你可能感兴趣的:(算法)