algorithm-in-python/string/manacher.py

41 lines
1.1 KiB
Python
Raw Permalink Normal View History

2018-07-08 23:28:29 +08:00
''' mbinary
#########################################################################
# File : manacher.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-07-08 23:28:29 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-07-06 15:56
# Description:
#########################################################################
'''
2020-04-15 12:28:20 +08:00
2018-07-08 23:28:29 +08:00
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
n = len(s)
2020-04-15 12:28:20 +08:00
s2 = '$#'+'#'.join(s)+'#@'
ct = [0]*(2*n+4)
mid = 1
for cur in range(1, 2*n+2):
if cur < mid+ct[mid]:
ct[cur] = min(ct[2*mid-cur], mid+ct[mid]-cur)
2018-07-08 23:28:29 +08:00
else:
2020-04-15 12:28:20 +08:00
ct[cur] = 1
while s2[cur-ct[cur]] == s2[cur+ct[cur]]:
ct[cur] += 1
if cur+ct[cur] > mid+ct[mid]:
mid = cur
2018-07-08 23:28:29 +08:00
mx = max(ct)
2020-04-15 12:28:20 +08:00
idxs = [i for i, j in enumerate(ct) if j == mx]
2018-07-08 23:28:29 +08:00
p = idxs[0]
for i in idxs:
2020-04-15 12:28:20 +08:00
if s2[i] == '#':
p = i
rst = s2[p-mx+1:p+mx].replace('#', '')
return rst