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.
思路
由于我做题没有按照顺序,前面做了几道也是回文的题,因此这道题也是同样的解法:动态规划。就是计算出来所有可能长度的子字符串是不是回文,中间计算的时候是按照长度来依次计算的,也就是说计算后面的值时用到了前面计算过的值。后面加那么多判断是为了可能提前结束计算。如果所有k和k+1长度的子字符串都不是回文的话,那么长度再增加也不会是回文。这个也是蕴含在计算过程中的。
class Solution {
public:
string longestPalindrome(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<bool> > isPalindrome;
bool preRes=true;
for(int l=1;l<=s.length();l++)
{
vector<bool> tmp;
bool res=false;
for(int i=0;i+l<=s.length();i++)
{
if(l==1)
tmp.push_back(true);
else if(l==2)
{
if(s[i]==s[i+l-1]) tmp.push_back(true);
else tmp.push_back(false);
}
else
{
if(s[i]==s[i+l-1]) tmp.push_back(isPalindrome[l-2-1][i+1]);
else tmp.push_back(false);
}
res=res||tmp[i];
}
isPalindrome.push_back(tmp);
if(!(res||preRes))
{
for(int j=0;j<isPalindrome[l-3].size();j++)
{
if(isPalindrome[l-3][j])
return s.substr(j,l-2);
}
}
preRes=res;
}
if(isPalindrome[s.length()-1][0])
return s;
else
{
for(int j=0;j<isPalindrome[s.length()-2].size();j++)
{
if(isPalindrome[s.length()-2][j])
return s.substr(j,s.length()-1);
}
}
return s;
}
};

本文详细阐述了使用动态规划解决寻找给定字符串中最长回文子串的问题,包括算法思路、代码实现及优化策略。通过逐步计算不同长度子串的回文属性,最终找到最长的回文子串。
5134

被折叠的 条评论
为什么被折叠?



