From 653b59fa20feab5f3d433a9ae648602743da6d2d Mon Sep 17 00:00:00 2001 From: Ayush Yadav <56931013+AyushYadav29@users.noreply.github.com> Date: Thu, 24 Oct 2019 12:37:34 +0530 Subject: [PATCH] Added Longest Palindrome Subsequence code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Problem: Given a sequence, find the length of the longest palindromic subsequence in it. As another example, if the given sequence is “BBABCBCAB”, then the output should be 7 as “BABCBAB” is the longest palindromic subseuqnce in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones. --- .../pedrovgs/Longest_Palindrome_Subsequence | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/main/java/com/github/pedrovgs/Longest_Palindrome_Subsequence diff --git a/src/main/java/com/github/pedrovgs/Longest_Palindrome_Subsequence b/src/main/java/com/github/pedrovgs/Longest_Palindrome_Subsequence new file mode 100644 index 00000000..3492c26e --- /dev/null +++ b/src/main/java/com/github/pedrovgs/Longest_Palindrome_Subsequence @@ -0,0 +1,27 @@ +public class Longest_Palindrome_Subsequence { +static int max(int x, int y) { +if(x>y) +return x; +else +return y; +} +static int lps(char s[], int i, int j) { + +if (i == j) { +return 1; +} +if (s[i] == s[j] && i + 1 == j) { +return 2; +} +if (s[i] == s[j]) { +return lps(s, i + 1, j - 1) + 2; +} +return max(lps(s, i, j - 1), lps(s, i + 1, j)); +} +public static void main(String[] args) { +String s = "ABBDCACBAD"; +int n = s.length(); +System.out.print("The longest palindrome subsequence is "+l +ps(s.toCharArray(), 0, n - 1)); +} +}