Created
November 7, 2017 20:02
-
-
Save anonymous/84f46ad7a35a50afff8096c0f7b23b38 to your computer and use it in GitHub Desktop.
Longest Common Subsequence Using Recursive Method
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
import java.util.Arrays; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class LongestCommonSubsequence { | |
public static void main(String args[]) { | |
long timestamp1 = System.currentTimeMillis(); | |
System.out.println("---------------Longest Common Subsequence Using Recursive Method-----------------"); | |
String string1 = "AGGTABNDSV"; | |
String string2 = "GXTXAYBDFGHOI"; | |
String longestCommonSubsequence = findLongestSubsequence(string1, string2); | |
System.out.println("LCS is "+new StringBuilder(longestCommonSubsequence).reverse().toString()); | |
long timestamp2 = System.currentTimeMillis(); | |
System.out.println(" Time Taken : "+(timestamp2-timestamp1)); | |
} | |
private static String findLongestSubsequence(String string1, String string2) { | |
char[] charArray1 = string1.toCharArray(); | |
char[] charArray2 = string2.toCharArray(); | |
int arraylength1 = string1.length() - 1; | |
int arraylength2 = string2.length() - 1; | |
String longestCommonSubsequence = ""; | |
if (arraylength1 < 0 || arraylength2 < 0) | |
return longestCommonSubsequence; | |
String newStr1 = String.valueOf(Arrays.copyOfRange(charArray1, 0, arraylength1)); | |
String newStr2 = String.valueOf(Arrays.copyOfRange(charArray2, 0, arraylength2)); | |
if (charArray1[arraylength1] == charArray2[arraylength2]) { | |
longestCommonSubsequence = longestCommonSubsequence + charArray1[arraylength1]; | |
longestCommonSubsequence = longestCommonSubsequence + findLongestSubsequence(newStr1, newStr2); | |
} else { | |
String res1 = findLongestSubsequence(newStr1, String.valueOf(charArray2)); | |
String res2 = findLongestSubsequence(String.valueOf(charArray1), newStr2); | |
if (res1.length() > res2.length()) { | |
longestCommonSubsequence = longestCommonSubsequence + res1; | |
} else | |
longestCommonSubsequence = longestCommonSubsequence + res2; | |
} | |
return longestCommonSubsequence; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment