<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword="palindromic-string"><em>palindromic</em></span> <span data-keyword="substring-nonempty"><em>substring</em></span> in <code>s</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;babad&quot;
<strong>Output:</strong> &quot;bab&quot;
<strong>Explanation:</strong> &quot;aba&quot; is also a valid answer.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;cbbd&quot;
<strong>Output:</strong> &quot;bb&quot;
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 1000</code></li>
	<li><code>s</code> consist of only digits and English letters.</li>
</ul>

class Solution {
public:
    string addPountSign(string s)
    {
        if (s.empty()) return "#";
        std::string res = "#";
        for (char c : s) {
            res += c;
            res += "#";
        }
        return res;
    }

    int calSizePalindrome(string s, int center)
    {
        int size = 0;
        int n = s.size();
        while (center - size >= 0 && center + size < n && s[center - size] == s[center + size]) {
            size++;
        }
        return size - 1;

    }

    string longestPalindrome(string s) {
        string t = addPountSign(s);
        vector<int> P = { 0 };
        int right = 0;
        int center = 0;
        int max_len = 0;
        int pos_max_len = 0;
        for (int i = 1; i < t.size(); i++)
        {
            if (i > right || (i == right && i < t.size() - 1) || (i < right && P[2 * center - i] * 2 + i >= right ))
            {
                int x = calSizePalindrome(t, i);
                if (x > max_len)
                {
                    max_len = x;
                    pos_max_len = i;
                }
                P.push_back(x);
                center = i;
                right = center + x;
            }
            else
            {
                P.push_back(P[2 * center - i]);
            }
        }

        string res;
        int start = (pos_max_len - max_len) / 2;
        int end = start + max_len;

        for (int i = start; i < end; i++) {
            res += s[i];
        }

        return res;
    }
};
240780