Topics
Given A string S, you is 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".
Give you a string. The minimum number of letters in the front, can make it a palindrome string. Solving
The basic practice on the net is to construct a string s+#+ inversion (s) and then the longest and suffix equal prefixes of the novelty string.
Then use the next array inside the KMP to solve the problem.
In fact, there is a black technology in this question ...
After preprocessing the string, it is possible to compare the two substrings in the time of O (1).
Link: Hash to find two substrings are equal (O (N) preprocessing O (1) comparison)
So it turned out to be a very violent solution. Code
Here only the solution of the hash, KMP of the solution on the web is everywhere const int MAXN = 50100;
Const unsigned long long SEED = 13331;
unsigned long long P[MAXN];
unsigned long long S[MAXN];
unsigned long long RS[MAXN];
string ts;
int n;
unsigned long long HS (int l, int r) {//positive if (L = = r) {return ts[l];
} l++;
r++;
return S[r]-S[L-1] * p[r-l + 1];
} unsigned long long RHS (int l, int r) {//reverse if (L = = r) {return ts[l];
} L = n-l-1;
r = n-r-1;
Swap (L, R);
l++;
r++;
return Rs[r]-RS[L-1] * p[r-l + 1];
} string Shortestpalindrome (string s) {ts = s;
P[0] = 1;
for (int i = 1; i < MAXN; i++) {p[i] = p[i-1] * SEED;
} n = s.size ();
for (int i = 1; I <= n; i++) {s[i] = s[i-1] * SEED + s[i-1];
} for (int i = 1; I <= n; i++) {rs[i] = rs[i-1] * SEED + s[n-i];
} int ans = n-1; for (int i = 0; i < N/2; i++) {if (HS (0, i) = = RHS (i + 1, i + 1 + i)){ans = min (ans, n-2 * (i + 1)); } if (2 * i + 2 < n && HS (0, i) = = RHS (i + 2, i + 2 + i)) {ans = min (ans, n-2 * (i + 1)
-1);
}} String ss = "";
for (int i = 0; i < ans; i++) {ss + = s[n-i-1];
} SS + = S;
return SS; }