Longest Palindromic Substring
Nov 11 '11
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.
暴力搜索的复杂度为O(n^2),下面这个做法是O(n)的,算法另外转载一篇文章来讲,完整的代码如下:
http://www.cnblogs.com/wuyiqi/archive/2012/06/25/2561063.html
string longestPalindrome(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int mx = 0;
int id = 0;
string ss(s.length()*2+1,'#');
for(int i = 0;i < s.length();i++)
ss[2*i+1] = s[i];
vector<int> P(ss.length(),0);
for(int i = 0;i < ss.length();i++)
{
if(i<mx) P[i] = min(P[2*id - i],mx - i);
else P[i] = 1;
for(;i-P[i]>=0 && i+P[i]< ss.length() && ss[i-P[i]]==ss[i+P[i]];P[i]++)
if(i + P[i] > mx) {
mx = i + P[i];
id = i;
}
}
int max_len = 0;
for(int i = 0; i < P.size();i++)
{
if(P[i] > max_len){
max_len = P[i];
id = i;
}
}
return s.substr((id - max_len+1)/2,max_len-1);
}