public class Program {
// Compute the Longest Common Subsequence (LCS) length using recursion
public static int lcs(char[] s1, char[] s2, int s1_len, int s2_len) {
// Base case: if either string is empty, LCS length is 0
if (s1_len == 0 || s2_len == 0)
return 0;
// If last characters match, include this character in LCS
if (s1[s1_len - 1] == s2[s2_len - 1])
return 1 + lcs(s1, s2, s1_len - 1, s2_len - 1);
// Otherwise, take the maximum LCS by:
// 1. Removing last char of s2
// 2. Removing last char of s1
return mymax(
lcs(s1, s2, s1_len, s2_len - 1),
lcs(s1, s2, s1_len - 1, s2_len)
);
}
// Simple helper to return the larger of two integers
public static int mymax(int a, int b) {
return (a > b) ? a : b;
}
public static void main(String[] args) {
// Input strings
String s1 = "accyrb";
String s2 = "cyxyazb";
// Convert to char arrays for recursive processing
char[] cs1 = s1.toCharArray();
char[] cs2 = s2.toCharArray();
// Compute and print the LCS length
System.out.println("The length of LCS is: " +
lcs(cs1, cs2, cs1.length, cs2.length));
}
}
/*
run:
The length of LCS is: 3
*/