题目描述

给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。

一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。

例如,”ace” 是 “abcde” 的子序列,但 “aec” 不是 “abcde” 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。

若这两个字符串没有公共子序列,则返回 0

示例1

  1. 输入:text1 = "abcde", text2 = "ace"
  2. 输出:3
  3. 解释:最长公共子序列是 "ace",它的长度为 3。

示例2

  1. 输入:text1 = "abc", text2 = "abc"
  2. 输出:3
  3. 解释:最长公共子序列是 "abc",它的长度为 3。

解题思路

注意子序列与子串的区别,子序列不要求连续,采用动态规划的思想,定义二维数组dp[i][j]表示数组arr1[0..i]与数组arr2[0..j]之间的最大公共子序列长度,转移方程为:
47 最长公共子序列 - 图1

  1. class Solution {
  2. public:
  3. int longestCommonSubsequence(string text1, string text2) {
  4. vector<vector<int>> dp(text1.length()+1, vector<int>(text2.length()+1, 0));
  5. int res = 0;
  6. for (int i=1; i<text1.length()+1; i++) {
  7. for (int j=1; j<text2.length()+1; j++) {
  8. if (text1[i-1] == text2[j-1])
  9. dp[i][j] = dp[i-1][j-1] + 1;
  10. else
  11. dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
  12. res = max(res, dp[i][j]);
  13. }
  14. }
  15. return res;
  16. }
  17. };