动态规划,写的比较糙。
class Solution {
public:
string longestPalindrome(string s) {
int max = 1;
int left = 0;
int n = s.size();
int** dp = new int*[n];
for(int i = 0; i < n; i++)
{
dp[i] = new int[n];
for(int j = 0; j > n; j++)
{
if(i == j)
{
dp[i][j] = 1;
}
else
{
dp[i][j] = 0;
}
}
}
for(int j = 0; j < n; j++)
{
for(int i = 0; i < j; i++)
{
if( s[i] != s[j])
{
dp[i][j] = 0;
}
else if(i == j-1 && s[i] == s[j])
{
dp[i][j] = 1;
}
else
{
dp[i][j] = dp[i+1][j-1];
}
if(dp[i][j] && j-i+1 > max)
{
max = j-i+1;
left = i;
}
}
}
for(int i = 0; i < n; i++)
{
delete [] dp[i];
}
delete [] dp;
string result = s.substr(left,max);
return result;
}
};