<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:
    int extend(int a, int b, int N, string s){
        int i = 0; 
        while(a-i >= 0 && b+i < N && s[a-i] == s[b+i]) i++; 
        return i; 
    }
    string longestPalindrome(string s) {
        string sm = "#";
        for(int i = 0; i < s.length(); i++){
            sm += s[i];
            sm += '#'; 
        }
        // cout << sm << '\n';
        int sm_len = sm.length();
        int z[1020*2] = {0};
        z[0] = 1; 
        int L = 0, R = 0; 
        
        for(int i = 1; i < sm_len; i++){
            int ii = L - (i-L); // i 的映射位置
            // int ii;   
            int n = R+1-i; // 已知回文的右範圍

            if(i > R){
                z[i] = extend(i, i, sm_len, sm);
                L = i; // L 回文的中間點
                R = i+z[i]-1; 
            }else if(z[ii] == n){ //能找到更大的回文
                z[i] = n + extend(i-n, i+n, sm_len, sm);
                L = i; 
                R = i+z[i]-1; 
            }else{ // 沒有更大的回文或已知這邊也是最大的回文
                z[i] = min(z[ii], n); // TODO: unknown
                // z[i] = z[ii];
            }            
        }

        int n = 0, p = 0; 
        for(int i = 0; i < sm_len; i++){
            if(z[i] > n){
                n = z[i];
                p = i; 
            }
        }

        string ans = "";
        // cout << p-z[p]+1 << ' ' << p+z[p] << '\n';
        for(int i = p-z[p]+1; i < p+z[p]; i++){
            if(i&1) ans += sm[i]; 
        }
        return ans; 
    }
};
216595