Skip to content

Commit 3587e2b

Browse files
author
Jiang
committed
增加Manacher算法的Python实现
1 parent aabeadd commit 3587e2b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

ebook/code/python/1.6:最长回文子串.py

+27
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,34 @@ def naiveLongestPalindromes(seq):
126126

127127
return l
128128

129+
130+
# implement manacher algorithm
131+
def pre_process(seq):
132+
res = ['#{}'.format(elem) for elem in seq]
133+
res.append('#$')
134+
res.insert(0,'^')
135+
return ''.join(res)
136+
137+
def manacher(seq):
138+
T = pre_process(seq)
139+
P = [0]*len(T)
140+
c,r = 0,0
141+
for i in range(1,len(T)):
142+
i_mirror = 2*c - i
143+
if r > i:
144+
P[i] = min(r-i, P[i_mirror])
145+
else:
146+
P[i] = 0
147+
while i+1+P[i] < len(T)-1 and i-1-P[i] >=0 and T[ i+1+P[i] ] == T[ i-1-P[i] ]:
148+
P[i] += 1
149+
if i + P[i] > r:
150+
c = i
151+
r = i+P[i]
152+
return max(P)
153+
154+
129155
if __name__ == '__main__':
130156
s = 'madam'
157+
print(manacher(s))
131158
print(max(fastLongestPalindromes(s), key=lambda x: x[0])[1])
132159
print(max(naiveLongestPalindromes(s), key=lambda x: x[0])[1])

0 commit comments

Comments
 (0)