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.
Subscribe to see which companies asked this question
class Solution {
public:
string longestPalindrome(string s) {
string str="#";
for (int i = 0; i < s.length(); ++i)
{
str+=s[i];
str+='#';
}
vector<int> vec(str.length(), 1);
int right = 0, index = 0, maxl=0, maxi=0;
for(int i = 0; i < str.length(); i++) {
if(i < right) {
if(i+vec[2*index-i]-1 < right) {
vec[i] = vec[2*index-i];
} else {
vec[i] = right-i+1;
for (int r=right+1, l=i-vec[i]; l >= 0 && r < str.length(); l--, r++) {
if(str[l]!=str[r]) break;
vec[i]+=1;
}
if(i+vec[i]-1 >= right) {
index = i;
right = i+vec[i]-1;
}
}
} else {
for(int l = i-1, r=i+1; l >= 0 && r < str.length(); l--, r++) {
if(str[l] != str[r]) break;
vec[i]+=1;
}
if(i+vec[i]-1 >= right) {
index = i;
right = i+vec[i]-1;
}
}
if(vec[i] > maxl) {
maxl = vec[i];
maxi = i;
}
}
string ans="", tmp="";
if(str[maxi] != '#')
tmp += str[maxi];
for (int i = 1; i < vec[maxi]; ++i)
{
if(str[maxi+i] == '#') continue;
ans += str[maxi+i];
}
string rans = ans;
reverse(rans.begin(), rans.end());
if(tmp == "") {
return rans+ans;
} else {
return rans+tmp+ans;
}
}
};