Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty())
{
return "";
}
if (1 == s.size())
{
return s;
}
int maxLen = 0;
int len = s.size();
int table[len][len] = {0};
for (int i = 0; i < len; i++)
{
table[i][i] = 1;
}
string longstr = s.substr(0, 1);
maxLen = 1;
for (int i = 0; i < (len - 1); i++)
{
if (s[i] == s[i + 1])
{
table[i][i+1] = 1;
maxLen = 2;
longstr = s.substr(i, maxLen);
}
else
{
table[i][i+1] = 0;
}
}
for (int l = 3; l <= len; l++)
{
for (int i = 0; i <= (len - l); i++)
{
int j = i + l - 1;
if (s[i] == s[j])
{
table[i][j] = table[i + 1][ j - 1];
if (table[i][j] == 1 && l > maxLen)
{
maxLen = j + 1 - i;
longstr = s.substr(i, maxLen);
}
}
else
{
table[i][j] = 0;
}
}
}
return longstr;
}
};