Just reimplemented the solution to this classic problem using Manacher algorithm in my mind. So neat idea :)
class Solution { public: string longestPalindrome(string s) { size_t slen = s.length(); if (slen < 2) return s; // inserting tokens to original string string ns = "#"; for (auto c : s) { ns += c; ns += "#"; } // size_t len = ns.length(); vector<size_t> rec(len, 0); int maxi = 1, maxr = 0; int ci = 1, r = 0; for (size_t i = 1; i < len; i++) { int myr = 0; // brand new index if (i <= (ci + r)) // can be reused due to symmetry { myr = std::min(rec[2 * ci - i], (ci + r) - i); } // expand to new inx towards end of string bool bMis = false; int max_ex = std::min(len - 1 - i, i); while (myr < max_ex) { myr++; if (ns[i + myr] != ns[i - myr]) { bMis = true; break; } } if (bMis) myr--; // book-keeping rec[i] = myr; if ((i + myr) > (maxi + maxr)) ci = i, r = myr; if (myr > maxr) // record max { maxi = i, maxr = myr; } } string raw = ns.substr(maxi - maxr, maxr * 2 + 1); string ret; for (auto c : raw) { if (c != '#') ret += c; } return ret; } };