From ecc1f491c0787b00363b18905042faa2bb73c126 Mon Sep 17 00:00:00 2001 From: its-sai <88180989+its-sai@users.noreply.github.com> Date: Wed, 19 Oct 2022 21:56:19 +0530 Subject: [PATCH] Create Longest Palindromic Subsequence I want to contribute by adding a very popular strings problem in your amazing repository --- .../strings/Longest Palindromic Subsequence | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/main/java/com/rampatra/strings/Longest Palindromic Subsequence diff --git a/src/main/java/com/rampatra/strings/Longest Palindromic Subsequence b/src/main/java/com/rampatra/strings/Longest Palindromic Subsequence new file mode 100644 index 00000000..f02236f8 --- /dev/null +++ b/src/main/java/com/rampatra/strings/Longest Palindromic Subsequence @@ -0,0 +1,51 @@ + import java.util.*; + import java.io.*; + + class home{ + public static void main(String args[]){ + Scanner sc= new Scanner (System.in); + int t=sc.nextInt(); + while(t-->0){ + String s=sc.next(); + Solution obj = new Solution(); + System.out.println(obj.longestPalinSubseq(s); + } + } + } + +class Solution +{ + public int longestPalinSubseq(String A) + { + + int n = A.length(); + + StringBuilder st = new StringBuilder(); + st.append(A); + st.reverse(); + + String B = st.toString(); + + // a palindrome reads the same from front and reverse. + // hence, the longest palindromic subsequence is + // basically the longest common subsequence in + // A and reverse(A) + int[][] dp = new int[n + 1][n + 1]; + for (int i = 0; i <= n; ++i) + { + for (int j = 0; j <= n; ++j) + { + if (i == 0 || j == 0) + dp[i][j] = 0; + else + { + if (A.charAt(i - 1) == B.charAt(j - 1)) + dp[i][j] = 1 + dp[i - 1][j - 1]; + else + dp[i][j] = Math.max (dp[i - 1][j], dp[i][j - 1]); + } + } + } + return dp[n][n]; + } +}