The meaning of problems
To a string $ s $, find the longest substring palindromic
answer
Template title horse-drawn vehicles algorithms. First, the pre-S $ $ string, each character in the left and right are plugged in a special symbol, such as #
the purpose is to ensure that the string length is an odd number. For example, abc
\ (\ rightarrow \) #a#b#c#
, \ abcd
(\ rightarrow \) #a#b#c#d#
. At the same time in order to guarantee $ while $ circulation does not exceed the border , in the beginning and end of the string after treatment plus special characters are not the same needs. For example, #a#b#c#
\ (\ rightarrow \) @#a#b#c#$
. (If the statement is a global variable, not the end of the insert special characters, because when it was declared, has been initialized: 0) and then make $ id: = $ palindromic sequence all previously been found in the boundary farthest palindrome center strings, $ mx: = $ has previously been found in all palindrome string boundary farthest boundaries palindrome string. Category talk:
- \ (I <MX = \) , \ (P [I] = min (MX - + I. 1, P [2 ID * - I]) \) . Since about $ $ $ I $ ID symmetry point J $ $ ( \ (J = 2 * ID - I \) ) the length of the palindromic sequence has been known, so $ p [i] = p [ j] $ may be established . If + p [i] $ i - part 1> mx $, so that more than $ MX $ string portion may not be a palindromic sequence at $ I $ centric. That's why here to take $ min $
- \ (i> MX \) , to use the most simple way to find $ i $ the center of the longest palindrome string
Finally, in the recording process of updating the maximum $ p $ p [I] of $ [i] - 1 $ line
int p[MAXN * 2];
char ma[MAXN * 2];
int Mana(char* s, int n) {
int m = 1;
// inite string s
ma[0] = '@';
for (int i = 0; i < n; ++i) {
ma[m++] = '#';
ma[m++] = s[i];
}
ma[m] = '#';
//printf("%s\n", ma);
int id = 0, mx = 0, ans = 0;
for (int i = 0; i < m; ++i) {
if (i < mx) p[i] = min(mx - i + 1, p[2 * id - i]);
else p[i] = 1;
while(ma[i - p[i]] == ma[i + p[i]]) p[i]++;
if (i + p[i] - 1 > mx) {
id = i;
mx = i + p[i] - 1;
ans = max(ans, p[i] - 1);
}
}
return ans;
}