1143. Longest Common Subsequence

Given two strings text1 and text2, return the length of their longest common subsequence.

subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

Example 1:

Input: text1 = "abcde", text2 = "ace" 
Output: 3  
Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  • 1 <= text1.length <= 1000
  • 1 <= text2.length <= 1000
  • The input strings consist of lowercase English characters only.

这题是一个dp, 普通dp公式是

如果s1[i]==s2[j]  dp[i][j]=dp[i-1][j-1] +1

否则  dp[i][j]=max(dp[i-1][j],dp[i][j-1])

时间复杂度是O(I*J); 空间复杂度也是; 但是通过这个dp公式可以发现,实际上空间可以优化,并不是I*J的空间都要被用到, 只有最近的两层会被用到,也就是 dp[i][j-1] 和 dp[i-1][j]

所以,优化版本变为  dp[2][j]; 这里dp[2][i]  或者 dp[2][j] 都可以; i%2表示相邻的循环层次的切换,

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>> dp(2, vector<int>(text2.size()+1,0));
        for(int i=1;i<=text1.size();++i)
            for(int j=1;j<=text2.size();++j)
            {
                if(text1[i-1]==text2[j-1]) dp[i%2][j]=dp[(i-1)%2][j-1]+1;
                else dp[i%2][j]=max(dp[(i-1)%2][j], dp[i%2][j?j-1:0]);
            }
        return dp[text1.size()%2].back();
    }
};
原文地址:https://www.cnblogs.com/lychnis/p/11960179.html