代码随想录算法训练营第五十六天|LeetCode583. 两个字符串的删除操作、LeetCode72. 编辑距离

一、LeetCode583. 两个字符串的删除操作

题目链接:583. 两个字符串的删除操作
1、dp数组及下标含义:
dp[i][j]表示下标为i-1之前的word1字符串和下标为j-1之前的word2字符串相同所需删除字符的最小操作步骤。
2、递推公式:

 if(word2[j - 1] == word1[i - 1]) dp[i][j] = dp[i - 1][j - 1];
 else {
        dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
      }

3、初始化:

 for(int i = 0; i <= word1.size(); i++) dp[i][0] = i;
 for(int j = 1; j <= word2.size(); j++) dp[0][j] = j;

4、遍历顺序:
由递推公式可知,dp[i][j]依赖于dp[i-1][j]、dp[i][j-1]和dp[i-1][j-1]。
5、打印dp数组
代码如下:

class Solution {
public:
    int minDistance(string word1, string word2) {
        vector<vector<int>>dp(word1.size() + 1, vector<int>(word2.size() + 1));
        for(int i = 0; i <= word1.size(); i++) dp[i][0] = i;
        for(int j = 1; j <= word2.size(); j++) dp[0][j] = j;

        for(int i = 1; i <= word1.size(); i++) {
            for(int j = 1; j <= word2.size(); j++) {
                if(word2[j - 1] == word1[i - 1]) dp[i][j] = dp[i - 1][j - 1];
                else {
                    dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1);
                }
            }
        }
        return dp[word1.size()][word2.size()];
    }
};

二、LeetCode72. 编辑距离

题目链接:72. 编辑距离
1、dp数组及其下标含义:
dp[i][j]表示下标i-1之前的字符串word1通过增、删、替换,改变成下标为j-1之前的字符串word2所需的最少步骤。
2、递推公式:

 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;

3、初始化:

 for(int i = 0; i <= word1.size(); i++) dp[i][0] = i;
 for(int j = 1; j <= word2.size(); j++) dp[0][j] = j;

4、遍历顺序:
从上到下,从左到右。
5、打印dp数组;
代码如下:

class Solution {
public:
    int minDistance(string word1, string word2) {
        vector<vector<int>>dp(word1.size() + 1, vector<int>(word2.size() + 1));

        for(int i = 0; i <= word1.size(); i++) dp[i][0] = i;
        for(int j = 1; j <= word2.size(); j++) dp[0][j] = j;

        for(int i = 1; i <= word1.size(); i++) {
            for(int j = 1; j <= word2.size(); 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[word1.size()][word2.size()];

    }
};

你可能感兴趣的:(C++算法题解,算法,leetcode,动态规划)