Total number of odd length palindrome sub | Function to find the total palindromic odd Length sub - sequences ; dp array to store the number of palindromic subsequences for 0 to i - 1 and j + 1 to n - 1 ; We will start with the largest distance between i and j ; For each Len , we fix our i ; For this i we will find our j ; Base cases ; If the characters are equal then look for out of bound index ; We have only 1 way that is to just pick these characters ; If the characters are not equal ; Subtract it as we have counted it twice ; We have just 1 palindrome sequence of Length 1 ; Else total ways would be sum of dp [ i - 1 ] [ i + 1 ] , that is number of palindrome sub - sequences from 1 to i - 1 + number of palindrome sub - sequences from i + 1 to n - 1 ; Driver code
def solve ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for Len in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if i + Len >= n : NEW_LINE INDENT break NEW_LINE DEDENT j = i + Len NEW_LINE if ( i == 0 and j == n - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 2 NEW_LINE DEDENT elif ( s [ i ] != s [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j + 1 <= n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i ] [ j + 1 ] NEW_LINE DEDENT if ( i - 1 < 0 or j + 1 >= n ) : NEW_LINE INDENT dp [ i ] [ j ] += 1 NEW_LINE DEDENT DEDENT elif ( s [ i ] != s [ j ] ) : NEW_LINE INDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j + 1 <= n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i ] [ j + 1 ] NEW_LINE DEDENT if ( i - 1 >= 0 and j + 1 <= n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] -= dp [ i - 1 ] [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT ways = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 or i == n - 1 ) : NEW_LINE INDENT ways . append ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT total = dp [ i - 1 ] [ i + 1 ] NEW_LINE ways . append ( total ) NEW_LINE DEDENT DEDENT for i in ways : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT s = " xyxyx " NEW_LINE solve ( s ) NEW_LINE