Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
代码如下:
class Solution {
public:
string longestPalindrome(string s) {
/*
DP 思路:时间复杂度O(n^2),空间复杂度O(n^2)
P[i][j]是记录i到j子串是不是回文串
P(i,j)={true,if the substring Si…Sj is a palindrome;false,if the substring Si…Sj is not a palindrome}
那么可以得到:P(i,j)=(P(i+1,j−1) && Si==Sj)
*/
if(s.size()<=2) return s;
vector<vector<bool>> dp(s.size(),vector<bool>(s.size(),0));
int maxLen=0,left=0,right=0;
//首先固定j,之后再从0到j去遍历i
for(int j=0;j<s.size();j++)//*****
{
for(int i=0;i<j;i++)//******
{
if(s[i]==s[j] && (j-i<=2 || **dp[i+1][j-1]**))
{
dp[i][j]=1;
if(j-i+1>maxLen)
{
maxLen=j-i+1;
left=i;
right=j;
}
}
}
}
return s.substr(left,right-left+1);
}
};