<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) {
        if (s.empty()) return "";
        vector<vector<int>> dp(s.size(), vector<int>(s.size(), -1));
        return f(s, 0, s.size() - 1, dp);
    }

private:
    string f(string &s, int start, int end, vector<vector<int>>& dp) {
        if (start > end) return "";
        if (start == end) return string(1, s[start]);
        if (dp[start][end] != -1) {
            return s.substr(start, dp[start][end]);
        }
        if (ispalindrome(s, start, end)) {
            dp[start][end] = end - start + 1;
            return s.substr(start, dp[start][end]);
        }
        string s1 = f(s, start, end - 1, dp);
        string s2 = f(s, start + 1, end, dp);
        if (s1.size() > s2.size()) {
            dp[start][end] = s1.size();
            return s1;
        }
        dp[start][end] = s2.size();
        return s2;
    }

    bool ispalindrome(string &s, int start, int end) {
        while (start < end) {
            if (s[start] != s[end]) return false;
            ++start;
            --end;
        }
        return true;
    }
};

470538