Given two strings text1 and text2, return the length of their longest common subsequence. Subsequence = delete some chars without changing order.
"abcde", "ace"3If chars match, extend LCS of shorter prefixes by 1. If not, take best of skipping one char from either string. Table fills bottom-up.
Comparing every subsequence of one string with every subsequence of the other is exponential. Instead, compare prefixes.
Let dp of i and j be the answer for the first i characters of the first string and the first j of the second. An empty prefix gives 0, so the first row and column are 0. If the two last characters match, take dp of i −1, j −1, plus 1. Otherwise, drop one character from either string, and take the larger of the two results. The bottom right cell is the answer.
Match means diagonal plus 1, mismatch means the larger of up and left. Prefix tables solve most two string problems.
Run the animation above on your own input, or watch the 1:52 video explanation of Longest Common Subsequence with a dry run and Java code.