<pre name="code" class="cpp" style="font-size: 14px; line-height: 26px;"><span style="font-family: Arial; background-color: rgb(255, 255, 255);">http://www.tuicool.com/articles/n6NfIrN</span>
动态规划刚刚重新学,这道题实在想不出来,百度了一下才发现 动态规划的时间复杂度最少都n方。。。。。。。。。。方向就考虑错了,收到了leetcode第三题的影响。
回文字符串的子串也是回文,P[i][j](表示以i开始以j结束的子串)是回文字符串,那么P[i+1][j-1]也是回文字符串。该问题可以分解成一系列子问题。
定义状态方程和转移方程:
P[i][j]=0表示子串[i,j]不是回文串 P[i][j]=1表示子串[i,j]是回文串
dp[i][j] = (s[i] == s[j] && dp[i+1][j-1] == true)
class Solution {
public:
string longestPalindrome(string s) {
int length = s.length();
if(length==1)
return s;
if(length==0)
return NULL;
bool dp[1000][1000] = {false};
int maxsublength = 0;
int start = 0;
for(int i=0;i<length;i++)
{
dp[i][i] = true;
if(i<length-1 && s.at(i)==s.at(i+1))
{
dp[i][i+1] = true;
maxsublength = 2;
start = i;
}
}
for(int len = 3;len<=length;len++)
{
for(int i = 0;i<=length-len;i++)
{
int end = i+len-1;
if(s.at(i) == s.at(end) && dp[i+1][end-1])
{
dp[i][end] = true;
if(len > maxsublength)
{
maxsublength = len;
start = i;
}
}
}
}
if(maxsublength>=2)
return s.substr(start,maxsublength);
return NULL;
}
};