Shortest Palindrome
Total Accepted: 13465 Total Submissions: 74427 Difficulty: Hard
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa"
, return "aaacecaaa"
.
Given "abcd"
, return "dcbabcd"
.
Hide Similar Problems
先用manacher求出以第一个字符开头的最长回文的长度,然后把剩下的字符逆序放在原始串的前面
class Solution { public: void preProcess(string &s,int sSize,string& copedStr){ for(int i=0;i<sSize;i++){ copedStr.push_back('*'); copedStr.push_back(s[i]); } copedStr.push_back('*'); } int longestPalindromeLengthStartWithFirstChar(string s) { int sSize = s.size(); if(sSize<=1){ return sSize; } string str; preProcess(s,sSize,str); int strSize = 2*sSize+1; vector<int> parr(strSize,1); int mid = 0; int left =-1,right = 1; int pl = -1, pr = 1; int radius = 0; for(;right<strSize;right++){ radius = 0; if(right>=pr){ while((right-radius>=0 && right+radius<strSize) && str[right-radius]==str[right+radius]){ radius++; } parr[right] = radius; }else{ left = mid - (right-mid); if(left - parr[left] +1 < pl+1){ parr[right] = left - pl; }else if(left - parr[left] +1 > pl+1){ parr[right] = parr[left]; }else{ radius = parr[left]-1; while((right-radius>=0 && right+radius<strSize) && str[right-radius]==str[right+radius]){ radius++; } parr[right] = radius; } } radius = parr[right] ; if(right + radius >= pr){ pr = right + radius ; pl = right - radius ; mid = right; } } int maxLen = 1; for(int i=1;i<strSize;i++){ if(i-parr[i]+1<=1){ int tmpRadius = i%2==0 ? parr[i]-1:parr[i]; if(tmpRadius>maxLen ){ maxLen = parr[i]-1; } } } return maxLen; } string shortestPalindrome(string s) { int j = longestPalindromeLengthStartWithFirstChar(s); string tmpStr; cout<<j<<endl; for(int i=s.size()-1;i>=j;i--){ tmpStr.push_back(s[i]); } return tmpStr+s; } };