Longest Palindromic Substring
Manacher algorithm
https://www.geeksforgeeks.org/manachers-algorithm-linear-time-longest-palindromic-substring-part-1/
brute-force solution:
for each substringin string s, check if it is palidromic
time plexity O(n^3)
two pointer solution:
improve brute-force solution
for each char c in s, since a palidormic string`s is symmetical, so we can use two pointer
left pointer at c-1 and right pointer at c+1, return False if s[left] != s[right] while left > -1 and right < len(s)
time complexity is O(n^2)
Manacher Solution:
problem of two pointer solution
1. compare smae char multiple time
for a string "aaa"
the first char 'a' need to compare 2 time, firts time at first a, second time use middle a as central
2. for palidromic string with odd / even length it need different way to handle
to improve these problem
1. add a char not exist as seperator, so all palidormic string have odd length
"aaa" -> "#a#a#a#"(7)
"aa" -> "#a#a#"(5)
2. store current max right distance(maxd) it can achieved by a char a as middle point
for a new char c at position cp, it must at right of a
if cp > maxd:
use c as middle point, until its not palidormic
else:
length of palidormic use c as middle >= length of palidormic use c' as middle
where c' is the pointer symmetical to c use a as middle point
1 |
class : |
近期评论