Distinct palindromic sub | Python3 implementation of the approach ; Function to return the count of distinct palindromic sub - strings of the given string s ; To store the positions of palindromic sub - strings ; Map to store the sub - strings ; Sub - strings of length 1 are palindromes ; Store continuous palindromic sub - strings ; Store palindromes of size 2 ; If str [ i ... ( i + 1 ) ] is not a palindromic then set dp [ i ] [ i + 1 ] = 0 ; Find palindromic sub - strings of length >= 3 ; End of palindromic substring ; If s [ start ] = = s [ end ] and dp [ start + 1 ] [ end - 1 ] is already palindrome then s [ start ... . end ] is also a palindrome ; Set dp [ start ] [ end ] = 1 ; Not a palindrome ; Return the count of distinct palindromes ; Driver code
import numpy as np ; NEW_LINE def palindromeSubStrs ( s ) : NEW_LINE INDENT dp = np . zeros ( ( len ( s ) , len ( s ) ) ) ; NEW_LINE m = { } ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT dp [ i ] [ i ] = 1 ; NEW_LINE m [ s [ i : i + 1 ] ] = 1 ; NEW_LINE DEDENT for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT dp [ i ] [ i + 1 ] = 1 ; NEW_LINE m [ s [ i : i + 2 ] ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ i + 1 ] = 0 ; NEW_LINE DEDENT DEDENT for length in range ( 3 , len ( s ) + 1 ) : NEW_LINE INDENT for st in range ( len ( s ) - length + 1 ) : NEW_LINE INDENT end = st + length - 1 ; NEW_LINE if ( s [ st ] == s [ end ] and dp [ st + 1 ] [ end - 1 ] ) : NEW_LINE INDENT dp [ st ] [ end ] = 1 ; NEW_LINE m [ s [ st : end + 1 ] ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ st ] [ end ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT return len ( m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abaaa " ; NEW_LINE print ( palindromeSubStrs ( s ) ) ; NEW_LINE DEDENT