<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 longestPalindrome(string s) {
        int n = s.size();
        string rev_s = s; // 复制s
        reverse(rev_s.begin(), rev_s.end()); // 倒置s
        int max_len = 0, end_idx = 0;
        
        // 建立一个二维数组来存储公共子串长度
        vector<vector<int>> dp(n+1, vector<int>(n+1, 0));
        
        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (s[i-1] == rev_s[j-1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                    // 检查子串是否是回文，且长度大于当前最长
                    if (dp[i][j] > max_len && isPalindrome(s.substr(i - dp[i][j], dp[i][j]))) {
                        max_len = dp[i][j];
                        end_idx = i;
                    }
                }
            }
        }
        return s.substr(end_idx - max_len, max_len);
    }
    
    bool isPalindrome(const string& str) {
        int left = 0, right = str.size() - 1;
        while (left < right) {
            if (str[left++] != str[right--]) {
                return false;
            }
        }
        return true;
    }
};

379844