From 6b95b02161741b47b5392fc5593e34ed83d9a734 Mon Sep 17 00:00:00 2001 From: Aman Shekhar Date: Sat, 22 Jun 2024 09:36:43 +0530 Subject: [PATCH] Create Print_LongestCommonSubsequence --- class_43/Print_LongestCommonSubsequence | 58 +++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 class_43/Print_LongestCommonSubsequence diff --git a/class_43/Print_LongestCommonSubsequence b/class_43/Print_LongestCommonSubsequence new file mode 100644 index 0000000..2a2fc83 --- /dev/null +++ b/class_43/Print_LongestCommonSubsequence @@ -0,0 +1,58 @@ +public class Solution { + public String longestCommonSubsequence(String text1, String text2) { + int n = text1.length(); + int m = text2.length(); + int[][] dp = new int[n + 1][m + 1]; + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + + StringBuilder lcs = new StringBuilder(); + int i = n, j = m; + while (i > 0 && j > 0) { + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { + lcs.append(text1.charAt(i - 1)); + i--; + j--; + } else if (dp[i - 1][j] > dp[i][j - 1]) { + i--; + } else { + j--; + } + } + + return lcs.reverse().toString(); + } + + public static void main(String[] args) { + Solution sol = new Solution(); + String text1 = "abcde"; + String text2 = "aced"; + System.out.println("LCS length: " + sol.longestCommonSubsequenceLength(text1, text2)); + System.out.println("LCS: " + sol.longestCommonSubsequence(text1, text2)); // Output: "ace" + } + + public int longestCommonSubsequenceLength(String text1, String text2) { + int n = text1.length(); + int m = text2.length(); + int[][] dp = new int[n + 1][m + 1]; + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= m; j++) { + if (text1.charAt(i - 1) == text2.charAt(j - 1)) { + dp[i][j] = dp[i - 1][j - 1] + 1; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[n][m]; + } +}