Classic question, nothing to say, directly on the Manacher, Time complexity O (n), Space complexity O (n), because an additional request for an array to store the length of the child palindrome at each location.
The essence of the algorithm:
1. Convert any odd, even length string to an odd number.
2. Use the right edge of the longest palindrome that has been obtained to reduce the number of repetitions, if the right border mx>i, then p[i] = min (mx-i, p[2*id-i]).
Hihocoder test data may be larger, if directly with C + + string concatenation strings directly to the tle, very curious why not using rvalue reference optimization, incredibly in the construction phase of the timeout,
Helpless can only be replaced by character array.
Impl:
1#include <string>2#include <iostream>3#include <cstdio>4#include <cstring>5 6 using namespacestd;7 8 Char* Preprocess (Char* STR,Char*tstr)9 {Ten intLen =strlen (str); One intj =0; ATstr[j++] ='#'; - for(inti =0; i < Len; ++i) { -Tstr[j++] =Str[i]; theTstr[j++] ='#'; - } -Tstr[j++] ='$'; -TSTR[J] =' /'; + returnTstr; - } + A at intManacher (Char* STR,Char*str1) - { - Char* Tstr =preprocess (str, str1); - intLen =strlen (TSTR); - if(len = =2)return 0; - in intMX =0, id; - int* p =New int[Len]; to for(inti =1; I < len-1; ++i) + { -P[i] = i < mx? Min (Mx-i, p[2*id-i]):0; the * while(tstr[i+p[i]+1] = = tstr[i-p[i]-1]) $p[i]++;Panax Notoginseng - if(P[i]+i >mx) the { +id = i, mx = p[i]+i; A } the } + - intmaxlen=1; $ for(inti =1; I < len-1; ++i) $MaxLen =Max (MaxLen, P[i]); - Delete[] p; - returnMaxLen; the } - Wuyi Charstr[1000010]; the Chartstr[2000020]; - Wu intMain () - { About intN; $scanf"%d", &n); - - while(n--) - { Ascanf"%s", str); +printf"%d\n", Manacher (str, tstr)); the } - $ return 0; the}View Code
Hihocoder (1032) longest palindrome substring