【力扣 | 01】5. 最长回文子串
5. 最长回文子串
解法:
class Solution {
public:
string longestPalindrome(string s)
{
if(s.size() < 2) return s;
string result;
vector<vector<bool>> dp(s.size() + 1, vector<bool>(s.size() + 1, false));
for(int i = 0; i < s.size(); i++) dp[i][i] = true;
int maxLen = 0;
int beginIndex = 0;
for(int i = s.size() - 1; i >= 0; i--)
{
for(int j = i; j < s.size(); j++)
{
if(s[i] == s[j])
{
if(j - i<= 1)
dp[i][j] = true;
else if(dp[i+1][j-1])
dp[i][j] = true;
}
if (dp[i][j] && j - i + 1 > maxLen)
{
maxLen = j - i + 1;
beginIndex = i;
}
}
}
result = s.substr(beginIndex,maxLen);
return result;
}
};