题目链接:https://leetcode.com/problems/longest-palindromic-substring/#/description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
class Solution {
public:
string longestPalindrome(string s) {
if(s.empty())
return "";
if(s.size() == 1)
return s;
int maxLen = 0;
string res = "";
vector<vector<bool>> dp(s.size(), vector<bool>(s.size(), false));
for(int i = s.size() - 1; i >= 0; i--) {
dp[i][i] = true;
if(1 > maxLen) {
maxLen = 1;
res = s.substr(i, 1);
}
for(int j = i + 1; j < s.size(); j++) {
if(s[i] == s[j] && ( i + 1 == j || dp[i + 1][j - 1])) {
dp[i][j] = true;
if(j - i + 1 > maxLen) {
maxLen = j - i + 1;
res = s.substr(i, j - i + 1);
}
}
}
}
return res;
}
};
class Solution {
public:
string longestPalindrome(string s) {
if(s.length()<=1)
return s;
vector<vector<bool>> dp(s.length(),vector<bool>(s.length(),false));
int startPos=0,maxlen=1;
for(int i=0;i<s.length();i++)
{
dp[i][i]=true;
if(i+1<s.length())
{
if(s[i]==s[i+1])
{
dp[i][i+1]=true;
maxlen=2;
startPos=i;
}
else
dp[i][i+1]=false;
}
}
for(int len=3;len<=s.length();len++)
{
for(int i=0;i<s.length()-len+1;i++)
{
if(dp[i+1][i+len-2] && s[i]==s[i+len-1])
{
dp[i][i+len-1]=true;
startPos=i;
maxlen=len;
}
else
dp[i][i+len-1]=false;
}
}
return s.substr(startPos,maxlen);
}
};