Longest Common Subsequence
Problem
Two words are given on two lines. Print the length of their longest common subsequence (letters in the same order in both words, but not necessarily next to each other).
Constraints
- 1 <= length <= 1000, lowercase or upper case letters
Examples
Input
abcde ace
Output
3
Solutions
The table cell (i, j) answers the same question for shorter prefixes. If the last letters are equal they are part of the answer. If not, one of them is not used, so we take the better of the two smaller problems.
/*
* Problem : Find the LCS length.
* Input : Two words.
* Output : The length.
* Approach: Fill a 2D table.
* Time : O(m * n)
* Space : O(m * n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(String a, String b) {
// Step 1: table[i][j] = the LCS length of the first i letters of a and the first j letters of b.
int[][] table = new int[a.length() + 1][b.length() + 1];
for (int i = 1; i <= a.length(); i++) {
for (int j = 1; j <= b.length(); j++) {
if (a.charAt(i - 1) == b.charAt(j - 1)) {
// Step 2: Equal letters extend the best answer of the shorter words by 1.
table[i][j] = table[i - 1][j - 1] + 1;
} else {
// Step 3: Otherwise skip one letter from a or one letter from b, and keep the better result.
table[i][j] = Math.max(table[i - 1][j], table[i][j - 1]);
}
}
}
// Step 4: The last cell has the answer for the full words.
return table[a.length()][b.length()];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (2)
- What is the LCS of a word and an empty word?
- What happens when the last letters differ?