Manacher’s algorithm which finds Longest Palindromic Substring in linear time. 1. first this conver input_string("xyx") into new_string("x|y|x") where odd positions are actual input characters. 2. for each character in new_string it find corresponding length and store,
( input_string )
| 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__': |
no test coverage detected