MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / palindromic_string

Function palindromic_string

strings/manacher.py:1–67  ·  view source on GitHub ↗

>>> palindromic_string('abbbaba') 'abbba' >>> palindromic_string('ababa') 'ababa' Manacher's algorithm which finds Longest palindromic Substring in linear time. 1. first this convert input_string("xyx") into new_string("x|y|x") where odd positions are actu

(input_string: str)

Source from the content-addressed store, hash-verified

1def palindromic_string(input_string: str) -> str:
2 """
3 >>> palindromic_string('abbbaba')
4 'abbba'
5 >>> palindromic_string('ababa')
6 'ababa'
7
8 Manacher's algorithm which finds Longest palindromic Substring in linear time.
9
10 1. first this convert input_string("xyx") into new_string("x|y|x") where odd
11 positions are actual input characters.
12 2. for each character in new_string it find corresponding length and
13 store the length and left,right to store previously calculated info.
14 (please look the explanation for details)
15
16 3. return corresponding output_string by removing 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 # we will store the starting and ending of previous furthest ending palindromic
31 # substring
32 left, right = 0, 0
33
34 # length[i] shows the length of palindromic substring with center i
35 length = [1 for i in range(len(new_input_string))]
36
37 # for each character in new_string find corresponding palindromic string
38 start = 0
39 for j in range(len(new_input_string)):
40 k = 1 if j > right else min(length[left + right - j] // 2, right - j + 1)
41 while (
42 j - k >= 0
43 and j + k < len(new_input_string)
44 and new_input_string[k + j] == new_input_string[j - k]
45 ):
46 k += 1
47
48 length[j] = 2 * k - 1
49
50 # does this string is ending after the previously explored end (that is right) ?
51 # if yes the update the new right to the last index of this
52 if j + k - 1 > right:
53 left = j - k + 1
54 right = j + k - 1
55
56 # update max_length and start position
57 if max_length < length[j]:
58 max_length = length[j]
59 start = j
60

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected