0%

leetcode-day-26

LeetCode 30 days Challenge - Day 26

本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。


Longest Common Subsequence

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

A 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:

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

Example 2:

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

Example 3:

1
2
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.

Solution

题目要求分析:给定两个字符串,求其中最长公共子串的长度。

解法:

本题需要注意区分子序列、子串:subsequence是子序列,子序列中各元素不需要连续,substring是子串,子串中每个元素必须是连续的。

本题是经典的动态规划题,维护一个二维动态规划数组dp,其中:

  1. i:1 - text1.length()j:1 - text2.length()
  2. dp[i][j]:text1[0:i-1]子串以及text2[0:j-1]子串之间最长公共子串的长度。
  3. 更新规则(对text1的每一个位置 - i-1,遍历text2所有的位置 - j-1):
    1. text1[i-1] == text2[j-1]dp[i][j] = dp[i-1][j-1] + 1;
    2. 否则: dp[i][j] = max(dp[i-1][j], dp[i][j-1]);

最终结果即为 dp[text1.length()][text2.length()]


1
2
3
4
5
6
7
8
9
10
int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>> dp(text1.length()+1, vector<int>(text2.length()+1, 0));
for (int i = 1; i <= text1.length(); i++) {
for (int j = 1; j <= text2.length(); j++) {
if (text1[i-1] == text2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[text1.length()][text2.length()];
}

传送门:Longest Common Subsequence

Karl