The most excellent solution might be Manacher's algorithm. Both time and space complexities are O(n). You can refere to
explaintation.

Of course, normally we can deal with string problems using suffix tree or suffix array to get O(n) time complexity.
So does this problem.

However, Manacher’s algorithm is simpler and easy to program compared with suffix tree or array.

// time complexity: O(n)
// space complexity: O(n)
classSolution3{private:stringpreProcess(conststring&s){stringret("^");// leading with special character
// insert delimeter
for(autoe:s){ret+='#';ret+=e;}ret+="#$";// ending with $
returnret;}public:stringlongestPalindrome(strings){stringt(preProcess(s));intlen=t.size();vector<int>p(len,0);// calculate array p[i]
// p[i] means how long it can be extended to left or right to form a palindrome
// centered with i, character i itself is included in this length.
// i.e.: p[i] = 2, means p[i-1] p[i] p[i+1] is a palindrome
// p[i] - 1 is the palindroem length of original string
intid=0,mx=0;for(inti=1;i<len-1;i++){p[i]=(mx>i)?min(p[2*id-i],mx-i):1;while(t[i+p[i]]==t[i-p[i]])p[i]++;if(p[i]+i>mx){id=i;mx=p[i]+i;}}intmaxLenId=1;for(inti=1;i<len;i++){if(p[i]>p[maxLenId]){maxLenId=i;}}// be careful with substr start point
returns.substr((maxLenId-p[maxLenId])/2,p[maxLenId]-1);}};