Longest Palindromic Substring | Set 1 | Python program ; A utility function to print a substring str [ low . . high ] ; This function prints the longest palindrome substring of st [ ] . It also returns the length of the longest palindrome ; get length of input string ; table [ i ] [ j ] will be false if substring str [ i . . j ] is not palindrome . Else table [ i ] [ j ] will be true ; All substrings of length 1 are palindromes ; check for sub - string of length 2. ; Check for lengths greater than 2. k is length of substring ; Fix the starting index ; Get the ending index of substring from starting index i and length k ; checking for sub - string from ith index to jth index iff st [ i + 1 ] to st [ ( j - 1 ) ] is a palindrome ; return length of LPS ; Driver program to test above functions
import sys NEW_LINE def printSubStr ( st , low , high ) : NEW_LINE INDENT sys . stdout . write ( st [ low : high + 1 ] ) NEW_LINE sys . stdout . flush ( ) NEW_LINE return ' ' NEW_LINE DEDENT def longestPalSubstr ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE table = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE maxLength = 1 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT table [ i ] [ i ] = True NEW_LINE i = i + 1 NEW_LINE DEDENT start = 0 NEW_LINE i = 0 NEW_LINE while i < n - 1 : NEW_LINE INDENT if ( st [ i ] == st [ i + 1 ] ) : NEW_LINE INDENT table [ i ] [ i + 1 ] = True NEW_LINE start = i NEW_LINE maxLength = 2 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT k = 3 NEW_LINE while k <= n : NEW_LINE INDENT i = 0 NEW_LINE while i < ( n - k + 1 ) : NEW_LINE INDENT j = i + k - 1 NEW_LINE if ( table [ i + 1 ] [ j - 1 ] and st [ i ] == st [ j ] ) : NEW_LINE INDENT table [ i ] [ j ] = True NEW_LINE if ( k > maxLength ) : NEW_LINE INDENT start = i NEW_LINE maxLength = k NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT k = k + 1 NEW_LINE DEDENT print " Longest ▁ palindrome ▁ substring ▁ is : ▁ " , printSubStr ( st , start , start + maxLength - 1 ) NEW_LINE return maxLength NEW_LINE DEDENT st = " forgeeksskeegfor " NEW_LINE l = longestPalSubstr ( st ) NEW_LINE print " Length ▁ is : " , l NEW_LINE