最大回文子串

def manacher(s):
    ss = '#'+'#'.join(s)+'#'
    print(ss)
    rl = [0]*len(ss)
    maxright = 0
    pos = 0
    maxlen = 0
    for i in range(len(ss)):
        # i在maxright左边时找对称回文串
        if i < maxright:
            rl[i] = min(rl[2*pos-i],maxright-i)
        else:
            rl[i] = 1
        # 左右两边扩展找回文串
        while i-rl[i] >= 0 and i+rl[i] < len(ss) and ss[i-rl[i]] == ss[i+rl[i]]:
            rl[i] += 1
        # 更新maxright和pos
        if rl[i]+i-1 > maxright:   
            maxright = i+rl[i]-1
            pos = i
        # 更新maxlen
        maxlen = max(maxlen,rl[i])
    return maxlen-1

动态规划:

def longestPalindrome(s):
    str_length = len(s)
    if str_length == 0:
        return ''
    max_length = 0
    i_start = 0
    for i in range(str_length):
        if i - max_length >= 1 and \
        	s[i - max_length - 1:i + 2] == \
        	s[i - max_length - 1:i + 2][::-1]:
            i_start = i - max_length - 1
            max_length += 2
            continue
        if i - max_length >= 0 and \
        s[i - max_length:i + 2] == \
        s[i - max_length:i + 2][::-1]:
            i_start = i - max_length
            max_length += 1
    return s[i_start:i_start + max_length+1]

你可能感兴趣的:(Coding)