Last active
September 10, 2019 07:12
-
-
Save tjkhara/0c0b73ad0102eb4c8ecc7c7459b9e299 to your computer and use it in GitHub Desktop.
lcs problem code
This file contains hidden or 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 getLongestCommonSubsequence(String a, String b) { | |
| int[][] matrix = new int[a.length() + 1][b.length() + 1]; | |
| for (int i = 0; i <= a.length(); i++) { | |
| for (int j = 0; j <= b.length(); j++) { | |
| if (i == 0 || j == 0) { | |
| matrix[i][j] = 0; | |
| } else if (a.charAt(i - 1) == b.charAt(j - 1)) { | |
| matrix[i][j] = 1 + matrix[i - 1][j - 1]; | |
| } else { | |
| matrix[i][j] = Math.max(matrix[i - 1][j], matrix[i][j - 1]); | |
| } | |
| } | |
| } | |
| return matrix[a.length()][b.length()]; | |
| } | |
| public static void main(String[] args) { | |
| String s1 = "atag"; | |
| String s2 = "atag"; | |
| System.out.println("Length of LCS is" + " " + getLongestCommonSubsequence(s1, s2)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment