<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 std::string();
        }

        size_t n = s.size();
        std::vector<int> table(n * n);

        for(size_t i = 0; i < n; ++i)
        {
            table[(n * i) + i] = 1;
        }

        // Lower triangle should all be zeros
        for(size_t row = 0; row < n; ++row)
        {
            size_t col = 0;
            while(col < row)
            {
                table[(n * row) + col] = 0;
                col += 1;
            }
        }

        // Upper triangle
        // i = row, j = col
        int start = 0;
        int end = 0;
        int max = 1;

        // Now handle palindromes of size 2
        for(size_t row = 0; row < (n - 1); ++row)
        {
            size_t col = row + 1;
            if(s[row] == s[col])
            {
                table[(n * row) + col] = 1;
                start = row;
                end = col;
                max = 2;
            }
            else
            {
                table[(n * row) + col] = 0;
            }
        }

        // Now handle palindromes of size
        for(size_t sz = 3; sz <= n; ++sz)
        {
            size_t end_row = n - sz;
            for(size_t row = 0; row <= end_row; ++row)
            {
                size_t col = row + (sz - 1);
                if(s[col] != s[row])
                {
                    table[(n * row) + col] = 0;
                }
                else
                {
                    int palin_val = table[(n * (row + 1)) + (col - 1)];
                    table[(n * row) + col] = palin_val;
                    if(palin_val == 1)
                    {
                        start = row;
                        end = col;
                        max = sz;
                    }
                }
            }
        }

        std::string ret;
        int cur = start;
        while(cur <= end)
        {
            ret.push_back(s[cur]);
            cur += 1;
        }

        return ret;
    }
};
252873