Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
原理是manacher算法。从中间向两边扩散,然后维护一个最大回文串的中心和最右端点的下标,当目前的中心在最大半径以内的时候,可以去找对称点,当目前中心在最大半径之外的时候,就要正常去匹配。
class Solution {
public:
string init(string s)
{
string ret;
ret="%#";
for(int i=0;i<s.size();i++)
{
ret +=s[i];
ret +='#';
};
return ret;
}
string longestPalindrome(string s) {
string nStr = init(s);
vector<int> R(nStr.size(),0);
int mx = 0,id = 0,start=0,maxLen=0;
for(int i = 1;i<nStr.size();i++)
{
if(mx>i)
R[i] = min(R[2*id-i],mx-i);
else
R[i] = 1;
while(nStr[i+R[i]]==nStr[i-R[i]])
++R[i];
if(i+R[i]>mx)
{
id = i;
mx = i+R[i];
}
if(R[i]-1>maxLen)
{
start = (i-R[i])/2;
maxLen = R[i]-1;
}
}
return s.substr(start,maxLen);
}
};