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
dp = { } NEW_LINE def solve ( s , c ) : NEW_LINE INDENT if ( len ( s ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT if ( s [ 0 ] == s [ 1 ] and s [ 0 ] == c ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( s + " ▁ " + c ) in dp : NEW_LINE INDENT return dp [ s + " ▁ " + c ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( s [ 0 ] == s [ len ( s ) - 1 ] and s [ 0 ] == c ) : NEW_LINE INDENT for c1 in range ( 97 , 123 ) : NEW_LINE INDENT if ( chr ( c1 ) != c ) : NEW_LINE INDENT ans = max ( ans , 1 + solve ( s [ 1 : len ( s ) - 1 ] , chr ( c1 ) ) ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == c ) : NEW_LINE INDENT for j in range ( len ( s ) - 1 , i , - 1 ) : NEW_LINE INDENT if ( s [ j ] == c ) : NEW_LINE INDENT if ( j == i ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = solve ( s [ i : j - i + 2 ] , c ) NEW_LINE break NEW_LINE DEDENT DEDENT break NEW_LINE DEDENT DEDENT DEDENT dp [ s + " ▁ " + c ] = ans NEW_LINE return dp [ s + " ▁ " + c ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abscrcdba " NEW_LINE ma = 0 NEW_LINE for c1 in range ( 97 , 123 ) : NEW_LINE INDENT ma = max ( ma , solve ( s , chr ( c1 ) ) * 2 ) NEW_LINE DEDENT print ( ma ) NEW_LINE DEDENT