Skip to content

Commit f4806eb

Browse files
Jitendra_Sharmayanglbme
Jitendra_Sharma
authored andcommitted
manacher's algorithm to find palindromic string (TheAlgorithms#676)
manacher's algorithm to find palindromic string in linear time complexity
1 parent ad0bc2b commit f4806eb

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

strings/manacher.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# calculate palindromic length from center with incresmenting difference
2+
def palindromic_length( center, diff, string):
3+
if center-diff == -1 or center+diff == len(string) or string[center-diff] != string[center+diff] :
4+
return 0
5+
return 1 + palindromic_length(center, diff+1, string)
6+
7+
def palindromic_string( input_string ):
8+
"""
9+
Manacher’s algorithm which finds Longest Palindromic Substring in linear time.
10+
11+
1. first this conver input_string("xyx") into new_string("x|y|x") where odd positions are actual input
12+
characters.
13+
2. for each character in new_string it find corresponding length and store,
14+
a. max_length
15+
b. max_length's center
16+
3. return output_string from center - max_length to center + max_length and remove all "|"
17+
"""
18+
max_length = 0
19+
20+
# if input_string is "aba" than new_input_string become "a|b|a"
21+
new_input_string = ""
22+
output_string = ""
23+
24+
# append each character + "|" in new_string for range(0, length-1)
25+
for i in input_string[:len(input_string)-1] :
26+
new_input_string += i + "|"
27+
#append last character
28+
new_input_string += input_string[-1]
29+
30+
31+
# for each character in new_string find corresponding palindromic string
32+
for i in range(len(new_input_string)) :
33+
34+
# get palindromic length from ith position
35+
length = palindromic_length(i, 1, new_input_string)
36+
37+
# update max_length and start position
38+
if max_length < length :
39+
max_length = length
40+
start = i
41+
42+
#create that string
43+
for i in new_input_string[start-max_length:start+max_length+1] :
44+
if i != "|":
45+
output_string += i
46+
47+
return output_string
48+
49+
50+
if __name__ == '__main__':
51+
n = input()
52+
print(palindromic_string(n))

0 commit comments

Comments
 (0)