File tree 1 file changed +27
-0
lines changed
1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -126,7 +126,34 @@ def naiveLongestPalindromes(seq):
126
126
127
127
return l
128
128
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
+
129
155
if __name__ == '__main__' :
130
156
s = 'madam'
157
+ print (manacher (s ))
131
158
print (max (fastLongestPalindromes (s ), key = lambda x : x [0 ])[1 ])
132
159
print (max (naiveLongestPalindromes (s ), key = lambda x : x [0 ])[1 ])
You can’t perform that action at this time.
0 commit comments