Skip to content

Commit fc5d6fd

Browse files
Create manachar_algorithm.py
1 parent 533d2b4 commit fc5d6fd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def get_palindrome_length(string, index):
2+
length = 1
3+
while index + length < len(string) and index - length >= 0:
4+
if string[index + length] == string[index - length]:
5+
length += 1
6+
else:
7+
break
8+
return length - 1
9+
10+
def interleave(string):
11+
ret = []
12+
for s in string:
13+
ret.extend(['#', s])
14+
ret.append('#')
15+
return ''.join(ret)
16+
17+
def manacher(string):
18+
right = 0
19+
center = 0
20+
string = interleave(string)
21+
P = map(lambda e: 0, xrange(len(string)))
22+
for i in xrange(1, len(string)):
23+
mirror = 2*center - i
24+
if i + P[mirror] <= right and mirror >= len(string) - i:
25+
P[i] = P[mirror]
26+
else:
27+
plength = get_palindrome_length(string, i)
28+
P[i] = plength
29+
if plength > 1:
30+
center = int(i)
31+
right = center + plength
32+
return [e/2 for e in P]
33+
34+
def get_palindrome_number(string):
35+
return sum(manacher(string))

0 commit comments

Comments
 (0)