题目如下
本题其实就是寻找最长的前缀回文串,显然可以通过kmp反向搜s串同时j不断回溯。
通过代码
class Solution {
public:
string shortestPalindrome(string s) {
int n = s.size();
if(n == 0)return "";
vector<int> next(n);
for(int i = 1,j = 0;i < n;i++){
while(j > 0 && s[i] != s[j])j = next[j - 1];
if(s[i] == s[j])j++;
next[i] = j;
}
int i = n - 1;
int j = 0;
while(i > 0){
if(s[i] == s[j]){
i--;
j++;
}else{
if(j > 0)j = next[j - 1];
else{
i--;
}
}
}
string a;
if(j == n - 1)a = "";
else{
a = s.substr(j + 1,n);
}
reverse(a.begin(),a.end());
return a + s;
}
};