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.
分析:
先把字符串每两个字符之间都放上#,这样可以把所有回文子串都变成奇数长度。
存一下当前延展到最右边的回文子串的信息。判断以i点为中心的回文子串有多长的时候就可以利用当前延展到最右边的子串的对称信息。
class Solution {
public:
string convert(string s)
{
string ans="^";
for(auto ch:s)
{
ans += "#";
ans += ch;
}
ans+="#%";
return ans;
}
string longestPalindrome(string s) {
if(s.empty())return s;
string tmps = s;
s = convert(s);
int n = s.length();
int center = 0, right = 0;
int *p = (int*)calloc(n,sizeof(int));
for(int i = 1; i < n-1; i++)
{
int j = 2*center - i;
p[i] = right > i? min(right - i, p[j]):1;
while(s[i+p[i]] == s[i-p[i]])
p[i]++;
if(i+p[i]-1 > right)
{
center = i;
right = i+p[i]-1;
}
}
int ans = 0, ansi = 0;;
for(int i = 1;i < n-1; i++)
{
if(p[i]>ans)
{
ans = p[i];
ansi = i;
}
}
free(p);
return tmps.substr((ansi - (ans-1) -1) / 2, ans - 1);
}
};