Given two strings s1 and s2, find the length of the longest string s3 that is a subsequence of s1 and also a substring of s2.
A subsequence is derived from a string by deleting some or no characters without changing the order of the remaining characters. A substring is a contiguous block of characters within a string.
Function Signature
def longest_subsequence_substring(s1: str, s2: str) -> int:
...
Rules
-
Return only the length of
s3
.
-
The empty string counts as both a subsequence and a substring, so the answer is 0 when
s1
and
s2
share no character.
Constraints
-
1 <= len(s1), len(s2) <= 1000
-
s1
and
s2
consist of lowercase English letters.
Examples
Input: s1 = "abcde", s2 = "ace"
Output: 3
"ace" is a subsequence of "abcde" (skip 'b' and 'd'), and it is the whole of s2, so it is also a substring of s2.
Input: s1 = "aebdc", s2 = "abcd"
Output: 3
"abc" is a substring of "abcd" and a subsequence of "aebdc" (indices 0, 2 and 4). "abcd" and "bcd" both fail because no 'd' comes after the 'c' at index 4 of s1.
Input: s1 = "ab", s2 = "axb"
Output: 1
"ab" is a subsequence of s1, but it is not contiguous in "axb". Every substring of "axb" longer than one character contains 'x', which s1 does not have, so the best length is 1.