Leetcode 1092. The shortest common supersequence (DAY 69) ---- dynamic programming learning period (first go to the second brush to do the hardest from the back of the sequence)

Original title

Insert picture description here


Code implementation (see the solution for the first brush part and self-solve part)

class Solution {
    
    
public:
    string shortestCommonSupersequence(string str1, string str2) {
    
    
        int strl1 = str1.size(),strl2 = str2.size(),i,j;
        string ret,temp;
        vector<vector<string>> dp(strl1+1,vector<string>(strl2+1,""));
        for(i=1;i<=strl1;++i)
        {
    
    
            for(j=1;j<=strl2;++j)
            {
    
    
                if(str1[i-1] != str2[j-1])
                {
    
    
                    if(dp[i-1][j].size() > dp[i][j-1].size())
                        dp[i][j] = dp[i-1][j];
                    else    dp[i][j] = dp[i][j-1];
                }
                else
                    dp[i][j] = dp[i-1][j-1] + str1[i-1];
            }
        }
        temp = dp[strl1][strl2];
        i=j=0;
        for(char ch:temp)
        {
    
    
            while(i<strl1 && str1[i]!=ch)
                ret+=str1[i++];
            while(j<strl2 && str2[j]!=ch)
                ret+=str2[j++];
            ret+=ch;++i,++j;
        }
        return ret+str1.substr(i)+str2.substr(j);
    }
};

Guess you like

Origin blog.csdn.net/qq_37500516/article/details/115201828