5- palindromic longest substring

Title: Given a string  s, to find  s the longest substring palindromic. You may assume that  s the maximum length of 1000.

start,maxlen = 0,0
def longestPalinrome(s):

    if len(s)<2:
        return s
    for i in range(len(s)):
        extendPal(s,i,i)

        extendPal(s,i,i+1)

    return s[start:start+maxlen]

def extendPal(s,left,right):
    global maxlen,start
    while left>=0 and right<len(s) and s[left]==s[right]:
        left-=1
        right+=1
    if maxlen<right-left-1:
        start = left+1
        maxlen = right-left-1

s1 = 'babad'
s2 = 'cbbd'
print(longestPalinrome(s1))
print(longestPalinrome(s2))

  Note:

The main idea is the center expansion method. Palindromic substring there may be an odd number, there may be an even number, the center of a character, and extend to two points in both cases to extend the character.

Guess you like

Origin www.cnblogs.com/kingshine007/p/11426663.html