Find the length of the longest subsequence that appears in both strings.
Given two strings text1 and text2, determine the length of their longest common subsequence (LCS).
A subsequence is formed by deleting zero or more characters without changing the order of the remaining characters. The characters of the subsequence do not need to be contiguous.
Your task is to compute the maximum possible length of a string that is a subsequence of both text1 and text2.
Notes
- The subsequence may be empty.
- You only need to return the length, not the subsequence itself.
Input Format
- Two strings
text1andtext2. - The strings consist of lowercase English letters in the standard LeetCode version.
Output Format
- Return a single integer: the length of the longest common subsequence of the two strings.
Constraints
- Characters are lowercase English letters in the standard version.
- A valid solution should run in time for strings of lengths and .
Example 1
Input
text1 = "abcde", text2 = "ace"
Output
3
Explanation
The longest common subsequence is "ace", which has length 3.
Example 2
Input
text1 = "abc", text2 = "abc"
Output
3
Explanation
The entire string is common, so the LCS length is 3.
Show 1 more example
Example 3
Input
text1 = "abc", text2 = "def"
Output
0
Explanation
The strings share no common subsequence except the empty one.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.