给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba"也是一个有效答案。
示例 2:
输入: "cbbd" 输出: "bb"
class Solution {
public:
string longestPalindrome(string s) {
if(s.size()<2) return s;
int n = s.size(),maxLen = 0, start = 0;
for(int i = 0; i < n - 1; i++){
searchPalindrome(s,i,i,start,maxLen);
searchPalindrome(s,i,i+1,start,maxLen);
}
return s.substr(start, maxLen);
}
void searchPalindrome(string s, int left, int right, int &start, int &maxLen){
while(left>=0&&right<s.size()&&s[left] == s[right]){
--left;
++right;
}
if(maxLen < right - left - 1){
start = left + 1;
maxLen = right - left - 1;
}
}
};
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() < 2)
return s;
int n = s.size(),maxLen = 0, start = 0;
for(int i = 0; i < n;){
if(n - i <= maxLen/2) break;
int left = i, right = i;
while(right < n - 1 && s[right+1] == s[right]) ++right;
i = right + 1;
while(right < n - 1 && left > 0 && s[right+1] == s[left-1]){
++right;
--left;
}
if(maxLen < right - left + 1){
maxLen = right - left + 1;
start = left;
}
}
return s.substr(start, maxLen);
}
};
class Solution {
public:
string longestPalindrome(string s) {
if(s.empty()) return "";
int dp[s.size()][s.size()] = {0}, left = 0, right = 0, len = 0;
for(int i = 0; i < s.size(); i++){
for(int j = 0; j < i; j++){
dp[j][i] = (s[i]==s[j]&&(i-j<2||dp[j+1][i-1]));
if(dp[j][i]&&len<i-j+1){
len = i-j+1;
left = j;
right = i;
}
}
dp[i][i] = 1;
}
return s.substr(left,right-left+1);
}
};
class Solution {
public:
string longestPalindrome(string s) {
string t = "$#";
for(int i = 0; i < s.size(); i++){
t += s[i];
t += '#';
}
int p[t.size()] = {0}, id = 0, mx = 0, resId = 0, resMx = 0;
for(int i = 0; i < t.size(); i++){
p[i] = mx > i ? min(p[2*id-i], mx-i) : 1;
while(t[i + p[i]] == t[i - p[i]]) ++p[i];
if(mx < i+p[i]){
mx = i + p[i];
id = i;
}
if(resMx < p[i]){
resMx = p[i];
resId = i;
}
}
return s.substr((resId - resMx) / 2, resMx-1);
}
};