Intuition
Compare the two strings prefix by prefix. When the last characters match, extend the diagonal LCS; otherwise take the better of dropping one character from either string.
Explanation
Definition
dp[i][j] = length of the LCS of the prefixes text1[:i] and text2[:j].
Transition
if text1[i-1] == text2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1 # matched one more character
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # drop a char from one side
Row 0 and column 0 are all zeros (an empty string shares nothing).
Worked example
text1 = "abcde", text2 = "ace":
amatchesa→ 1,cmatchesc→ 2,ematchese→ 3.- Non-matching cells inherit the best neighbour.
dp[5][3] = 3→ LCS is"ace".
Complexity
- Time: O(m·n).
- Space: O(m·n) (reducible to O(min(m,n))).
Implementation
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
}