<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:
    bool find(int left, int right, string &s, string &ans, vector<vector<int>> &dp) {
        if (left > right) return false;
        if (left == right) {
            return true;
        }

        if(dp[left][right] != -1) return dp[left][right];

        bool isPalindrome = false;
        
        if (s[left] == s[right]) {
            if (left + 1 == right) { // Two characters that are the same
                isPalindrome = true;
            } else {
                isPalindrome = find(left + 1, right - 1, s, ans, dp);
            }
            
            if (isPalindrome) {
                if (ans.size() < right - left + 1) {
                    ans = s.substr(left, right - left + 1);
                }
                return dp[left][right] = true;
            }
        }
        
        // Explore both possibilities if current characters do not match
        find(left, right - 1, s, ans, dp);
        find(left + 1, right, s, ans, dp);

        return dp[left][right] = false;
    }

    string longestPalindrome(string s) {
        string ans;
        ans+=s[0];
        
        int n = s.size();
        vector<vector<int>> dp(n, vector<int>(n, -1));
        
        find(0, s.size() - 1, s, ans, dp);
        return ans;
    }
};

307289