题目:
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) {
int max = 0;
string res = " ";
if(s.size()==0)
return res;
if(s.size()==1)
return s;
const int len = s.size();
bool dp[1001][1001];//采用动态规划,存储中间过程,否则会超时
//dp[0][0] = true;
fill_n(&dp[0][0], 1001 * 1001, false);
for (int i = 1; i < s.size(); i++)
{
for (int j = 0; j <= i; j++)
{
if (s[i] == s[j] && ((i-j) < 3 || dp[i - 1][j + 1]))
{
dp[i][j] = true;
if (max < i - j+1)
{
max = i - j + 1;
res = s.substr(j, i - j + 1);
}
}
}
}
return res;
}
};
点评:
解此题的方法为常规的字符串子串+动态规划存储中间过程