牛客题霸 [最长公共子序列] C++题解/答案

题目描述

给定两个字符串str1和str2,输出连个字符串的最长公共子序列。如过最长公共子序列为空,则输出-1。

题解:

dp经典问题

代码:

class Solution {
   
public:
    /** * longest common subsequence * @param s1 string字符串 the string * @param s2 string字符串 the string * @return string字符串 */
    
    string LCS(string s1, string s2) {
   
        // write code here
        int len1 = s1.size();
        int len2 = s2.size();
        
       string a=solve(len1,len2,s1,s2);
        return a;
    }
    string solve(int len1,int len2,string s1,string s2)
    {
   
        vector<vector<string> > dp(len1 + 1, vector<string>(len2 + 1, ""));
        string temp,temp1,temp2;
         for(int i = 1; i <= len1; ++i)
        {
   
            for(int j = 1; j <= len2; ++j)
            {
   
                if(s1[i - 1] == s2[j - 1])
                {
   
                    temp = dp[i - 1][j - 1];
                    temp += s1[i - 1];
                    dp[i][j] = temp;
                }
                else
                {
   
                    temp1 = dp[i - 1][j];
                    temp2 = dp[i][j - 1];
                    if(temp1.size() > temp2.size()){
   
                        dp[i][j] = temp1;
                    }else{
   
                        dp[i][j] = temp2;
                    }
                }
            }
        }
                if (dp[len1][len2] == "")
            return "-1";
        else
            return dp[len1][len2];
    }
};