<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:
    pair<pair<int,int>,int> sol(string& s,int i,int j,vector<vector<pair<pair<int,int>,int>>>&dp){
        if(j<i) return {{0,0},1};
        if(i==j) {
            return {{i,i},1};
        }
        if(dp[i][j].second!=-1) return dp[i][j];
        pair<int,int>t={0,0};
        if(s[i]==s[j]){
            pair<pair<int,int>,int> f = sol(s,i+1,j-1,dp);
            if(f.second) t={i,j};
        }
        pair<pair<int,int>,int> a = sol(s,i,j-1,dp);
        pair<pair<int,int>,int> b = sol(s,i+1,j,dp);
        int al =a.first.second-a.first.first;
        int bl =b.first.second-b.first.first;
        if(t.second-t.first>al &&t.second-t.first>bl) return dp[i][j] = {t,1};
        if(al>t.second-t.first &&al>bl) return dp[i][j] = {{a.first.first,a.first.second},0};
        return dp[i][j]= {{b.first.first,b.first.second},0};
    }
    string longestPalindrome(string s) {
        int n =s.size();
        string ans="";
        vector<vector<pair<pair<int,int>,int>>>dp(n,vector<pair<pair<int,int>,int>>(n,{{0,0},-1}));
        pair<pair<int,int>,int> f= sol(s,0,n-1,dp);
        for(int i=f.first.first;i<=f.first.second;i++){
            ans+=s[i];
        }
        return ans;
    }
};
482630