/*** Introduction to algorithms, second edition * 15.4 Longest Common subsequence * @ author **/public class longestcommonsubsequence {/*** calculate the longest common subsequence of two strings * @ Param x string x * @ Param Y string y * @ return the longest public sub-sequence of the two strings */public static string LCS (string X, string y) {int M = x. length (); int n = y. length (); int [] [] C = new int [M + 1] [n + 1]; // construct the computing matrix for (INT I = 1; I <= m; I ++) {for (Int J = 1; j <= N; j ++) {If (X. charat (I-1) = y. charat (J-1) {// if the same right bottom C [I] [J] = C [I-1] [J-1] + 1 ;} else if (C [I-1] [J]> = C [I] [J-1]) {// move C [I] [J] = C [I-1] [J];} else {C [I] [J] = C [I] [J-1] ;}} return output (X, Y, C, M, N ). tostring ();}/*** iterative output. * @ Param x string x * @ Param y string y * @ Param C calculation matrix * @ Param I row Index * @ Param J column Index * @ return output Longest Common subsequence */ private Static stringbuilder output (string X, string y, int [] [] C, int I, Int J) {if (I = 0 | j = 0) {return New stringbuilder ();} if (X. charat (I-1) = y. charat (J-1) {return output (X, Y, C, I-1, J-1 ). append (X. charat (I-1);} else if (C [I] [J] = C [I-1] [J]) {return output (X, Y, C, I-1, j);} else {return output (X, Y, C, I, J-1);} import JUnit. framework. testcase; public class longestcommonsubsequencetest extends testcase {public void testlcm () {assertequals ("bcba", longestcommonsubsequence. LCS ("abcbdab", "bdcaba "));}}