|
| 1 | +package SummerTrainingGFG.DynamicProgramming; |
| 2 | + |
| 3 | +import java.lang.reflect.Array; |
| 4 | +import java.util.Arrays; |
| 5 | + |
| 6 | +/** |
| 7 | + * @author Vishal Singh |
| 8 | + */ |
| 9 | +public class LongestCommonSubsequence { |
| 10 | + /* |
| 11 | + * Subsequence is picking some characters in same order but may not be contiguous |
| 12 | + * Substring means need to pick continuous characters |
| 13 | + * Subsequence of CDA -> "","C","D","A","CD","CA","DA","CDA" |
| 14 | + * 2^N POSSIBLE SUBSEQUENCE |
| 15 | + * Substring of CDA -> "","C","D","A","CD","DA","CDA" |
| 16 | + * LCS Of "ABCDGH" and "AEDFHR" is "ADH" length = 3 |
| 17 | + * */ |
| 18 | + |
| 19 | + /* |
| 20 | + * RECURSIVE SOLUTION*/ |
| 21 | + static int lcs(String s1, String s2, int m, int n) { |
| 22 | + if (m == 0 || n == 0) { |
| 23 | + return 0; |
| 24 | + } |
| 25 | + if (s1.charAt(m - 1) == s2.charAt(n - 1)) { |
| 26 | + return 1 + lcs(s1, s2, m - 1, n - 1); |
| 27 | + } else { |
| 28 | + return Math.max(lcs(s1, s2, m - 1, n), lcs(s1, s2, m, n - 1)); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + /* |
| 33 | + * MEMOIZATION - Theta(m*n)*/ |
| 34 | + static int[][] memoize; |
| 35 | + |
| 36 | + static int lcsMemoize(String s1, String s2, int m, int n) { |
| 37 | + if (memoize[m][n] != -1) { |
| 38 | + return memoize[m][n]; |
| 39 | + } |
| 40 | + if (m == 0 || n == 0) { |
| 41 | + memoize[m][n] = 0; |
| 42 | + } |
| 43 | + if (s1.charAt(m - 1) == s2.charAt(n - 1)) { |
| 44 | + memoize[m][n] = 1 + lcs(s1, s2, m - 1, n - 1); |
| 45 | + } else { |
| 46 | + memoize[m][n] = Math.max(lcs(s1, s2, m - 1, n), lcs(s1, s2, m, n - 1)); |
| 47 | + } |
| 48 | + return memoize[m][n]; |
| 49 | + } |
| 50 | + /* |
| 51 | + * TABULATION - Theta(m*n)*/ |
| 52 | + static int lcsTabulation(String s1,String s2){ |
| 53 | + int m = s1.length(); |
| 54 | + int n = s2.length(); |
| 55 | + int[][] dp = new int[m+1][n+1]; |
| 56 | + for (int i = 0; i <= m; i++) { |
| 57 | + dp[i][0] = 0; |
| 58 | + } |
| 59 | + for (int i = 0; i <= n; i++) { |
| 60 | + dp[0][i] = 0; |
| 61 | + } |
| 62 | + for (int i = 1; i <= m; i++) { |
| 63 | + for (int j = 1; j <= n; j++) { |
| 64 | + if (s1.charAt(i-1) == s2.charAt(j-1)){ |
| 65 | + dp[i][j] = 1 + dp[i-1][j-1]; |
| 66 | + }else { |
| 67 | + dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + return dp[m][n]; |
| 72 | + } |
| 73 | + public static void main(String[] args) { |
| 74 | + System.out.println(lcs("axyz", "baz", 4, 3)); |
| 75 | + |
| 76 | + int m = 4; |
| 77 | + int n = 3; |
| 78 | + memoize = new int[m + 1][n + 1]; |
| 79 | + for (int[] row : memoize) { |
| 80 | + Arrays.fill(row, -1); |
| 81 | + } |
| 82 | + System.out.println(lcsMemoize("axyz","baz",m,n)); |
| 83 | + |
| 84 | + System.out.println(lcsTabulation("axyz","baz")); |
| 85 | + |
| 86 | + } |
| 87 | +} |
0 commit comments