Skip to content

Commit c9812c8

Browse files
fix: preserve Manacher boundary palindromes and literal separators
1 parent 6e03a48 commit c9812c8

1 file changed

Lines changed: 10 additions & 18 deletions

File tree

‎strings/manacher.py‎

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,19 @@ def palindromic_string(input_string: str) -> str:
77
88
Manacher's algorithm which finds Longest palindromic Substring in linear time.
99
10-
1. first this convert input_string("xyx") into new_string("x|y|x") where odd
10+
1. first this convert input_string("xyx") into new_string("|x|y|x|") where odd
1111
positions are actual input characters.
1212
2. for each character in new_string it find corresponding length and
1313
store the length and left,right to store previously calculated info.
1414
(please look the explanation for details)
1515
16-
3. return corresponding output_string by removing all "|"
16+
3. return the corresponding slice of the original input string
1717
"""
1818
max_length = 0
1919

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]
20+
# Surround each character with separators so boundary palindromes have the
21+
# same representation as interior palindromes.
22+
new_input_string = "|" + "|".join(input_string) + "|"
2923

3024
# we will store the starting and ending of previous furthest ending palindromic
3125
# substring
@@ -58,13 +52,11 @@ def palindromic_string(input_string: str) -> str:
5852
max_length = length[j]
5953
start = j
6054

61-
# create that string
62-
s = new_input_string[start - max_length // 2 : start + max_length // 2 + 1]
63-
for i in s:
64-
if i != "|":
65-
output_string += i
66-
67-
return output_string
55+
# Map the transformed bounds back to the input. Removing separators by value
56+
# would also remove literal "|" characters from the palindrome.
57+
palindrome_start = (start - max_length // 2) // 2
58+
palindrome_end = (start + max_length // 2) // 2
59+
return input_string[palindrome_start:palindrome_end]
6860

6961

7062
if __name__ == "__main__":

0 commit comments

Comments
 (0)