Last active
May 27, 2018 05:00
-
-
Save thmain/162305c44c3638dc22f63625a6a730ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LongestCommonSubsequence { | |
public static int LCS(String A, String B) { | |
if (A.length() == 0 || B.length() == 0) { | |
return 0; | |
} | |
int lenA = A.length(); | |
int lenB = B.length(); | |
// check if last characters are same | |
if (A.charAt(lenA - 1) == B.charAt(lenB - 1)) { | |
// Add 1 to the result and remove the last character from both | |
// the strings and make recursive call to the modified strings. | |
return 1 + LCS(A.substring(0, lenA - 1), B.substring(0, lenB - 1)); | |
} else { | |
// Remove the last character of String 1 and make a recursive | |
// call and remove the last character from String 2 and make a | |
// recursive and then return the max from returns of both recursive | |
// calls | |
return Math.max( | |
LCS(A.substring(0, lenA - 1), B.substring(0, lenB)), | |
LCS(A.substring(0, lenA), B.substring(0, lenB - 1))); | |
} | |
} | |
public static void main(String[] args) { | |
String A = "ACBDEA"; | |
String B = "ABCDA"; | |
System.out.println("LCS :" + LCS(A, B)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment