Longest Common Subsequence
Implement longestCommonSubsequence
Given two strings, find the length of their longest common subsequence — the longest sequence of characters that appears in both strings in the same relative order, though not necessarily touching. If the two strings share nothing in common this way, the answer is 0.
Comparing the two strings one trailing character at a time exposes a clean split: when the last characters of both remaining prefixes agree, that character has to belong to some longest common subsequence, so it's taken and both prefixes shrink together. When they disagree, the best answer either ignores the last character of the first string or the last character of the second — trying both and keeping the larger result is always correct, since one of those two prefixes must still contain an optimal answer. Filling a table of these prefix-pair answers from the smallest prefixes upward turns an exponential search into a single pass over every (i, j) pair exactly once.
Example 1:
Input: text1 = "abcde", text2 = "ace"
Output: 3
Example 2:
Input: text1 = "abc", text2 = "def"
Output: 0
Example 3:
Input: text1 = "", text2 = "abc"
Output: 0
+ 7 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ text1.length, text2.length ≤ 12 - ●
text1 and text2 consist only of lowercase English letters
text1 =
abcde
text2 =
ace