Problem 186
Longest Common Subsequence
Medium · 20 pts · String, Dynamic Programming
Problem
You are given two strings S and T. A subsequence keeps the order of characters but may skip some of them. Find the length of the longest common subsequence: the longest string that is a subsequence of both S and T. Use a table where dp[i][j] is the answer for the first i characters of S and the first j characters of T. If S[i - 1] = T[j - 1], then dp[i][j] = dp[i - 1][j - 1] + 1; otherwise dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).
Input
Two lines: strings S and T of lowercase letters.
Output
Print the length of the LCS.
Constraints
1 <= |S|, |T| <= 1000
Example input
abcde ace
Example output
3
Explanation
"ace" can be read inside "abcde" by taking a, skipping b, taking c, skipping d and taking e, and it is the whole of the second string. So the longest common subsequence is "ace", of length 3.