<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.size()==1) return s;
        if(s.size()==2){
            if(s[0]==s[1]) return s;
            else s[0];
        }
        vector<vector<int>> dp(s.size(),vector<int>(s.size(),0));
        int max=0; string ans="";
        for(int l=1;l<=s.size();l++){
            for(int i=0;i<s.size()-l+1;i++){
                if(l==1) {
                    if(max<1) {max=1; ans=s[i];}
                    dp[i][i]=1;
                }else if(l==2){
                    if(s[i]==s[i+1]){
                        if(max<2) {max=2; ans=s.substr(i,2);}
                        dp[i][i+1]=1;
                    }
                }else{
                    int i1=i,i2=i+(l-1);
                    if(s[i1]==s[i2]&&dp[i1+1][i2-1]){
                        if(l>max) { max=l; ans=s.substr(i1,l);}
                        dp[i1][i2]=1; 
                    }
                }
            }
        }
        return ans;
    }
};
307289