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 | Input: text1 = "abcde", text2 = "ace" |
Example 2:
1 | Input: text1 = "abc", text2 = "abc" |
Example 3:
1 | Input: text1 = "abc", text2 = "def" |
Constraints:
1 <= text1.length <= 1000
1 <= text2.length <= 1000
- The input strings consist of lowercase English characters only.
Solution
题目要求分析:给定两个字符串,求其中最长公共子串的长度。
解法:
本题需要注意区分子序列、子串:subsequence是子序列,子序列中各元素不需要连续,substring是子串,子串中每个元素必须是连续的。
本题是经典的动态规划题,维护一个二维动态规划数组dp,其中:
i:1 - text1.length()
;j:1 - text2.length()
;dp[i][j]
:text1[0:i-1]子串以及text2[0:j-1]子串之间最长公共子串的长度。- 更新规则(对text1的每一个位置 - i-1,遍历text2所有的位置 - j-1):
- 当
text1[i-1] == text2[j-1]
:dp[i][j] = dp[i-1][j-1] + 1;
- 否则:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
- 当
最终结果即为 dp[text1.length()][text2.length()]
。
1 | int longestCommonSubsequence(string text1, string text2) { |
传送门:Longest Common Subsequence
Karl