Content deleted Content added
Improve readability |
Format code |
||
Line 55:
For example, consider the input string "abacaba". By the time it gets to the "c", Manacher's algorithm will have identified the length of every palindrome centered on the letters before the "c". At the "c", it runs a loop to identify the largest palindrome centered on the "c": "abacaba". With that knowledge, everything after the "c" looks like the reflection of everything before the "c". The "a" after the "c" has the same longest palindrome as the "a" before the "c". Similarly, the "b" after the "c" has a longest palindrome that is ''at least'' the length of the longest palindrome centered on the "b" before the "c". There are some special cases to consider, but that trick speeds up the computation dramatically.{{cn|date=March 2022}}
Longest_Palindrome(string S, string S') {
// between each character (including outer boundaries) // note: length(S') = length(PalindromeRadii) = 2 × length(S) + 1
array PalindromeRadii = [0,...,0]
Center = 0
Radius = 0
// for the longest
// it can be higher on later iterations. // going to Center+Radius while Center-(Radius+1) >= 0 and
Center+(Radius+1) < length(S') and
S'[Center-(Radius+1)] = S'[Center+(Radius+1)] {
Radius = Radius+1
// Save the radius of the longest palindrome in the array
Line 82 ⟶ 91:
OldRadius = Radius
Center = Center+1
// following loop.
Radius = 0
// a palindrome has a "mirrored" character reflected across its center, we▼
// Because Center lies inside the old palindrome and every
// can use the data that was precomputed for the Center's mirrored point. ▼
// reflected across its center, we can use the data that was
MirroredCenter = OldCenter - (Center - OldCenter)
MaxMirroredRadius = OldCenter + OldRadius - Center
// So, MirroredCenter and Center have the same sized palindrome▼
// The palindrome centered at MirroredCenter is entirely
// contained in the palindrome centered at OldCenter So,
PalindromeRadii[Center] = PalindromeRadii[MirroredCenter]
Center = Center+1
// palindrome at
// end at the edge of the OldCenter
// the palindrome at OldCenter would be bigger
PalindromeRadii[Center] = MaxMirroredRadius
Center = Center+1
// the edge of the palindrome centered at OldCenter, the // recheck unnecessarily Radius = MaxMirroredRadius
// (Radius / 2), which means a palindrome's size is equal to its
// corresponding Radius value in PalindromeRadii
longest_palindrome_in_S = max(PalindromeRadii)
}
|