string
longest prefix palindrome
- use LSP:
compute_lsp(t + sep + t[: : -1])
count all palindromes
idea
- start from
mid
, until mid < n
- expand to the
right
to cover duplicates
- after that,
right
will be mid
for the next iteration
- expand to both
left
and right
implementation
complexity
find longest palindrome - Manacher’s algorithm
idea
- add a special character
.
in between all characters to make all palindrome of odd length and add special characters at start and end as sentinels
- calculate the DP array
max_radius
where max_radius[center]
= max radius of the palindrome at center
- after calculated
max_radius[center]
:
max_radius
up to center
are calculated
- try to use it to calculate for
new_center
from center + 1
to center + max_radius[center]
:
- we can only use the palindromes that ends before or at
right_bound = center + max_radius[center]
- so maximum radius we can use for
new_center
is radius_bound
is right_bound - new_center
- use
mirror_center
which is the mirror of new_center
over center
- if longest palindrome at
mirror_center
is doesn’t reach the bound (i.e. max_radius[mirror_center] < radius_bound
)
- then longest palindrome at
new_center
must also be the same (i.e. max_radius[new_center] = max_radius[mirror_center]
)
- then increase
next_center
by 1
- if longest palindrome at
mirror_center
is over the bound (i.e. max_radius[mirror_center] > radius_bound
)
- then longest palindrome at
new_center
must ends at the bound (i.e. max_radius[mirror_center] = radius_bound
)
- then increase
next_center
by 1
- if longest palindrome at
mirror_center
end right at the bound (i.e. max_radius[mirror_center] == radius_bound
)
- then longest palindrome at
new_center
could ends at or over the bound (i.e. max_radius[mirror_center] = radius_bound
)
- so we update its
radius = radius_bound
and try to expand it in the next iteration
implementation
complexity
- Time: O(n)
- at each iteration, either
center
or center + max_radius[center]
increases
- Space: O(n)
misc
- similar idea to the Z-function algorithm.
- references: