Posted onInLeetcode
,
MediumViews: Valine: Symbols count in article: 4kReading time ≈4 mins.
Description
Difficulty: Medium
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
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.
For example, "ace" is a subsequence of "abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
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, text2.length <= 1000
text1 and text2 consist of only lowercase English characters.
Solution - 1: Dynamic Programming
We can compare the last two characters c1, c2 (if exist) of the string s1, s2
if they’re equal, LSE(s1, s2) = LSE(s1 without c1, s2 without c2) + 1
if not equal, LSE(s1, s2) = max{ LSE(s1 without c1, s2), LSE(s1, s2 without c2)}
classSolution{ publicintlongestCommonSubsequence(String text1, String text2){ return dp(text1, text2); } privateintdp(String text1, String text2){ if (text1 == "" || text2 == "") { return0; } int length1 = text1.length(); int length2 = text2.length(); // get the last character of both strings char lastChar1 = text1.charAt(length1-1); char lastChar2 = text2.charAt(length2-1); // recurrence relation if (lastChar1 == lastChar2) { return1 + longestCommonSubsequence(text1.substring(0, length1-1), text2.substring(0, length2-1)); } else { return Math.max( longestCommonSubsequence(text1.substring(0, length1-1), text2), longestCommonSubsequence(text1, text2.substring(0, length2-1))); } } }
Time Limit Exceeded at about half of the test cases since some subproblems are calculated multiple times, we should apply dynamic programming using memorization