Manacher algorithm O (n)
Because for even palindrome, it is necessary to expand from the imaginary axis, Ab,ba, so as follows:
First, the original string processing, all with a marker, such as # (special characters can be any, for the results of the calculation will not affect)
1221--> #1 #2#2#1#
121--> #1 #2#1#
The longest palindrome string length m is evaluated according to the processed string, so the length of the original string's oldest palindrome string is M/2
Variable:
1:parra[] Store palindrome radius: The length of a palindrome radius that can be expanded in a position, such as #1 #2#2#1#,2 position parra[3] = 4
2:int PR can sweep to the right of the palindrome position #1 #2#1# in position 3 PR = 6
3:int Index when the PR is updated, index is also updated, pointing to the current most central position in 2 index=3
Process:
When the required position I of the palindrome radius analysis is as follows:
1: The first case can directly determine the palindrome radius of I, PR unchanged, because there is no expansion
2: The second case, I ' left on the left side of index, PR does not change, (no expansion) can also directly determine the palindrome radius of I position
3: The third case, I ' left to drink index left to repeat, need to start from the "right large position to continue to expand"
How to calculate complexity:
If the extension succeeds, the description exceeds the current right large update PR
4: The fourth case must be violently expanded
Every time the inspection, either failed, or successful expansion, as long as the success of the expansion, PR must be updated, and the longest expansion is also 2n, so the "expansion" of the action and PR height-related;
When the algorithm is optimized by variables, this complexity is generally related to the increment of this variable.
Manacher algorithm Longest palindrome string