Length of longest Palindromic Subsequence of even length with no two adjacent characters same | To store the values of subproblems ; Function to find the Longest Palindromic subsequence of even length with no two adjacent characters same ; Base cases If the string length is 1 return 0 ; If the string length is 2 ; Check if the characters match ; If the value with given parameters is previously calculated ; If the first and last character of the string matches with the given character ; Remove the first and last character and call the function for all characters ; If it does not match ; Then find the first and last index of given character in the given string ; Take the substring from i to j and call the function with substring and the given character ; Store the answer for future use ; Driver code ; Check for all starting characters
var dp = new Map ( ) ; function solve ( s , c ) { if ( s . length == 1 ) return 0 ; if ( s . length == 2 ) { if ( s [ 0 ] == s [ 1 ] && s [ 0 ] == c ) return 1 ; else return 0 ; } if ( dp . has ( s + " " + c ) ) return dp . get ( s + " " + c ) ; var ans = 0 ; if ( s [ 0 ] == s [ s . length - 1 ] && s [ 0 ] == c ) { for ( var c1 = ' ' . charCodeAt ( 0 ) ; c1 <= ' ' . charCodeAt ( 0 ) ; c1 ++ ) if ( String . fromCharCode ( c1 ) != c ) ans = Math . max ( ans , 1 + solve ( s . substring ( 1 , s . length - 1 ) , String . fromCharCode ( c1 ) ) ) ; } else { for ( var i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == c ) { for ( var j = s . length - 1 ; j > i ; j -- ) if ( s [ j ] == c ) { if ( j == i ) break ; ans = solve ( s . substring ( i , j + 1 ) , c ) ; break ; } break ; } } } dp . set ( s + " " + c , ans ) ; return ans ; } var s = " " ; var ma = 0 ; for ( var c1 = ' ' . charCodeAt ( 0 ) ; c1 <= ' ' . charCodeAt ( 0 ) ; c1 ++ ) ma = Math . max ( ma , solve ( s , String . fromCharCode ( c1 ) ) * 2 ) ; document . write ( ma ) ;