Java Program for Longest Palindromic Subsequence | DP-12
Last Updated :
13 Aug, 2021
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 subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.
1) Optimal Substructure:
Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1].
If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2.
Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)).
Following is a general recursive solution with all cases handled.
Java
class GFG {
static int max( int x, int y)
{
return (x > y) ? x : y;
}
static int lps( char seq[], int i, int j)
{
if (i == j) {
return 1 ;
}
if (seq[i] == seq[j] && i + 1 == j) {
return 2 ;
}
if (seq[i] == seq[j]) {
return lps(seq, i + 1 , j - 1 ) + 2 ;
}
return max(lps(seq, i, j - 1 ), lps(seq, i + 1 , j));
}
public static void main(String[] args)
{
String seq = "GEEKSFORGEEKS" ;
int n = seq.length();
System.out.printf( "The length of the LPS is %d" ,
lps(seq.toCharArray(), 0 , n - 1 ));
}
}
|
Output:
The length of the LPS is 5
Dynamic Programming Solution
Java
class LPS {
static int max( int x, int y) { return (x > y) ? x : y; }
static int lps(String seq)
{
int n = seq.length();
int i, j, cl;
int L[][] = new int [n][n];
for (i = 0 ; i < n; i++)
L[i][i] = 1 ;
for (cl = 2 ; cl <= n; cl++) {
for (i = 0 ; i < n - cl + 1 ; i++) {
j = i + cl - 1 ;
if (seq.charAt(i) == seq.charAt(j) && cl == 2 )
L[i][j] = 2 ;
else if (seq.charAt(i) == seq.charAt(j))
L[i][j] = L[i + 1 ][j - 1 ] + 2 ;
else
L[i][j] = max(L[i][j - 1 ], L[i + 1 ][j]);
}
}
return L[ 0 ][n - 1 ];
}
public static void main(String args[])
{
String seq = "GEEKSFORGEEKS" ;
int n = seq.length();
System.out.println( "The length of the lps is " + lps(seq));
}
}
|
Output
The length of the lps is 5
Please refer complete article on Longest Palindromic Subsequence | DP-12 for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...