Hihocoder (1032) longest palindrome substring

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.