【LeetCode】583. Delete Operation for Two Strings (C++)


Source of subject: https://leetcode-cn.com/problems/delete-operation-for-two-strings/

Title description

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same. Each step can delete one character in any string.

Example:

Input: "sea", "eat"
Output: 2
Explanation: The first step changes "sea" to "ea", and the second step changes "eat" to "ea".

Tip:

The length of the given word does not exceed 500.
The characters in a given word only contain lowercase letters.

General idea

  • Classic dynamic programming problems
  • Five steps of dynamic programming:
    • Determine the meaning of the dp array and subscripts: dp[i][j] represents the character string word1 ending in i-1 and the character string word2 ending in j-1
    • 确定递推公式:
      d p [ i ] [ j ] = { d p [ i − 1 ] [ j − 1 ] ( i f w o r d 1 [ i − 1 ] = = w o r d 2 [ j − 1 ] ) e l s e m i n ( m i n ( d p [ i ] [ j − 1 ] + 1 , d p [ i − 1 ] [ j ] + 1 ) , d p [ i − 1 ] [ j − 1 ] + 2 ) dp[i][j]= \left \{ \begin{array} {c}dp[i-1][j-1]{\quad}(if{\quad}word1[i-1]==word2[j-1]) \\else \\min(min(dp[i][j-1]+1,dp[i-1][j]+1),dp[i-1][j-1]+2){\quad} \end{array} \right. dp[i][j]=dp[i1][j1](ifword1[i1]==word2[j1])elsemin(min(dp[i][j1]+1,dp[i1][j]+1),dp[i1][j1]+2)
  • carry on
    • How to define and initialize dp array
    • Determine the traversal order
    • Example to derive dp array
      Insert picture description here

Dynamic programming

  • When initializing, we need to traverse dp[i][0] and dp[0][j], because this is the initial state of the array dp, that is, to initialize word1 or word2 as an empty string
  • After confirming these five steps, the idea is clear
class Solution {
    
    
public:
    int minDistance(string word1, string word2) {
    
    
        int len1 = word1.size(), len2 = word2.size();
        vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1));
        for (int i = 0 ; i <= len1 ; ++i)   dp[i][0] = i;
        for (int j = 0 ; j <= len2 ; ++j)   dp[0][j] = j;
        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];
                }
                else{
    
    
                    dp[i][j] = min(min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1] + 2);
                }
            }
        }
        return dp[len1][len2];
    }
};

Complexity analysis

  • Time complexity: O(m*n). n is the length of the array
  • Space complexity: O(m*n). n is the length of the array, a two-dimensional dp array is maintained, the two-dimensional length is the length of word1, and the one-dimensional array in the two-dimensional is the length of word2

Guess you like

Origin blog.csdn.net/lr_shadow/article/details/115003239