Title
Given a string s, you can convert it to a palindrome by adding characters in front of the string. Find and return the shortest palindrome string that can be converted in this way.
Idea: The key is to find the longest palindrome prefix string of string s, you can construct its reverse string rev, long string
, find the nxt value of the last position of s2, that is, the length of the longest palindrome prefix string of the corresponding string s.
class Solution {
public:
//KMP寻找最长前缀回文串
string shortestPalindrome(string s) {
int n = s.size();
string rev = s;
reverse(rev.begin(),rev.end());
string s2 = s + "#" +rev;
int n2 = s2.size();
vector<int> nxt(n2+1,-1);
int i = 0,j = -1;
nxt[0] = -1;
while(i < n2) {
if(j == -1 || s2[j] == s2[i]) {
++i;++j;
nxt[i] = j;
}
else j = nxt[j];
}
return rev.substr(0,n-nxt[n2])+s;
}
};