Skip to content

Instantly share code, notes, and snippets.

@dkohlsdorf
Last active March 13, 2019 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkohlsdorf/217fdcaa19646c697ce5 to your computer and use it in GitHub Desktop.
Save dkohlsdorf/217fdcaa19646c697ce5 to your computer and use it in GitHub Desktop.
Longest Common Subsequence
public class LongestCommonSubsequence {
public static int length(String x, String y) {
int N = x.length();
int M = y.length();
int lcs[][] = new int[N + 1][M + 1];
for(int i = 1; i < N + 1; i++) {
for(int j = 1; j < M + 1; j++) {
if(x.charAt(i - 1) == y.charAt(j - 1)) {
lcs[i][j] = lcs[i - 1][j - 1] + 1;
} else {
lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
}
}
}
return lcs[N][M];
}
public static void main(String[] args) {
System.out.println(length("abcs", "abcs"));
System.out.println(length("abcs", "abs"));
System.out.println(length("abcs", "as"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment