Using the horse-drawn vehicle algorithm, the time complexity is O (n), the algorithm is explained in detail in the previous article.
////main.cpp//Longest Substring////Created by Bowie Hsu on 14/11/21.//Copyright (c) 2014 Bowie Hsu. All rights reserved.//#include<iostream>#include<string>#include<sstream>#include<vector>#include"stdio.h"#include"ctype.h"using namespacestd;classSolution { Public: //preprocessing, adding the # number to the original string stringPreprosess (strings) {intn=s.length (); //string oss;StringStream OSS;//call the StringStream in SstreamOSS <<'^'; for(intI=0; i<n; ++i) OSS<<"#"<<S[i]; OSS<<'#'; OSS<<'$'; returnOss.str (); } stringLongestpalindrome (strings) {stringoutput; intmx=0; intId=0; stringL=preprosess (s); intn=l.length (); int*p=New int[n]; //Manacher Algorithm for(intI=1; i<n-1;++i) {//Simple notationp[i]= (mx>i)? min (Mx-i, p[2*id-i]):1; while(l[i+p[i]]==l[i-P[i]]) ++P[i]; if(p[i]+i>mx) {mx=p[i]+i; ID=i; } } //find the position and number of the most large string intmaxnum=0; intCenter=0; for(intI=1; i<n-1; ++i) {if(p[i]>maxnum) {Maxnum=P[i]; Center=i; } } returnS.substr ((center-maxnum)/2, maxnum-1);//returns a string } };intMain () {stringinput="CCD"; stringans; Solution x; Ans=x.longestpalindrome (input); cout<<ans<<Endl;}
Longest palindromic Substring Problem solving report