2-D Dynamic Programming Two strings
566. Print a Longest Common Subsequence
You are given two strings, s1 and s2. Return one of the longest strings that is a subsequence of both.
A subsequence of a string is what is left after deleting some of its letters, or none, without changing
the order of the rest. "ace" is a subsequence of "abcde", but "eca" is not. The letters do not have to
sit next to each other.
Often several longest common subsequences exist, and any of them is correct. If the strings share no letter,
return the empty string "". Answers are shown in double quotes. When your string is a subsequence of both,
the result shows its length, as a common subsequence of length 3. Otherwise it shows the first thing wrong
with it, such as answer[1] = 'e' has no match in s1 after answer[0] = 'n' at index 5. Positions count
from 0.
Example 1
Input: s1 = "listen", s2 = "silent"
"len"Explanation: In "listen" the letters of "len" sit at indexes 0, 4 and 5, and in "silent" at 2, 3 and 4.
"ien" and "sen" are also correct. No common subsequence has 4 letters.
Example 2
Input: s1 = "moon", s2 = "sky"
""Explanation: The strings share no letter, so the only common subsequence is the empty one.
Example 3
Input: s1 = "coffee", s2 = "office"
"offe"Explanation: Both fs and the first e of each string line up in order. The c cannot join them: it comes first in
"coffee" but after both fs in "office".
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s1.length, s2.length ≤ 3000s1ands2hold only lowercase English letters.
Clarifying questions
What you would ask an interviewer before writing any code.