Last active
May 13, 2020 00:28
-
-
Save lbbedendo/02663629da3871b74cde63210856ef83 to your computer and use it in GitHub Desktop.
Longest Common Subsequence in java
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.time.Duration; | |
import java.time.Instant; | |
public class LongestCommonSubsequence { | |
public int lcsRecursive(char[] a, char[] b, int i, int j) { | |
if (a.length == i || b.length == j) | |
return 0; | |
else if (a[i] == b[j]) | |
return 1 + lcsRecursive(a, b, i + 1, j + 1); | |
else | |
return Math.max(lcsRecursive(a, b, i + 1, j), lcsRecursive(a, b, i, j + 1)); | |
} | |
public int lcsMemoization(char[] a, char[] b) { | |
int m = a.length; | |
int n = b.length; | |
int l[][] = new int[m + 1][n + 1]; | |
for (int i = 1; i <= m; i++) { | |
for (int j = 1; j <= n; j++) { | |
if (a[i-1] == b[j-1]) | |
l[i][j] = l[i-1][j-1] + 1; | |
else | |
l[i][j] = Math.max(l[i-1][j], l[i][j-1]); | |
} | |
} | |
return l[m][n]; | |
} | |
public static void main(String[] args) { | |
var a = "mhunuzqrkzsnidwbun"; | |
var b = "szulspmhwpazoxijwbq"; | |
calculateRecursively(a, b); | |
calculateWithMemoization(a, b); | |
a = "AGGTAB"; | |
b = "GXTXAYB"; | |
calculateRecursively(a, b); | |
calculateWithMemoization(a, b); | |
} | |
private static void calculateRecursively(String a, String b) { | |
var lcs = new LongestCommonSubsequence(); | |
var start = Instant.now(); | |
int r = lcs.lcsRecursive(a.toCharArray(), b.toCharArray(), 0, 0); | |
var end = Instant.now(); | |
var duration = Duration.between(start, end); | |
System.out.println(String.format("LCS (recursive) for %s and %s is %d", a, b, r)); | |
System.out.println("Time spent: " + duration); | |
} | |
private static void calculateWithMemoization(String a, String b) { | |
var lcs = new LongestCommonSubsequence(); | |
var start = Instant.now(); | |
int r = lcs.lcsMemoization(a.toCharArray(), b.toCharArray()); | |
var end = Instant.now(); | |
var duration = Duration.between(start, end); | |
System.out.println(String.format("LCS (memoization) for %s and %s is %d", a, b, r)); | |
System.out.println("Time spent: " + duration); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment