Marathon algorithm:
The marathon algorithm is used to calculate the longest palindrome string in a string (symmetric strings, such as Aba Abba).
First, we get a string s and then add # to each character in S.
Example: s= "ABCB" t= "a#b#c#b"
Each of our T-strings t[i] extends D characters so that T[i-d,i+d] is a palindrome string. You will immediately find out that D is the length of the longest back character string centered on T[i.
We create a P array, which is the length of the p array equal to the length of T, and the value of each p[i] represents the length of the maximum number of back character strings that correspond to the T[i] center.
As follows:
*************************
Look at p, we can immediately find the longest palindrome string length is p[6], the corresponding string is "Abaaba".
Have you found that the previous odd palindrome string and even palindrome string have become elegant after adding # (hint: This is just for the convenience of explaining, not the necessary steps in the algorithm code).
Now, imagine you draw a line in the middle of the palindrome string "Abaaba", and you will find that the numbers on both sides of the p are also symmetric about the line. Not only this string, you try "ABA" is the same situation.
Is this a coincidence? Answer is also, say is not also not. It only happens under certain conditions, however, we have made great progress.
Let's take a look at the more complex string "BABCBABCBACCBA".
*****************************
Show a build process from P based T, assuming you have completed part of P. The vertical line marks the normal middle C of the palindrome string "ABCBABCBA", and two vertical dashed lines are marked back to the left and right boundaries of the character string.
You are in the I position, and I position the mirror position about C is I '. How can you quickly calculate the value of P[i]?
We see that i=13,i ' = 9, we need to calculate is p[13].
*****************************
The area covered by the two green solid lines is symmetric about C. Let's take a look at I mirror I ', apparently p[i ']=p[i]=1. P[i] must be 1, because
Leetcode Algorithm Marathon algorithm (Manacher ' s Algorithm) (unfinished)