You are given a string s
. You can convert s
to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: s = "aacecaaa" Output: "aaacecaaa"
Example 2:
Input: s = "abcd" Output: "dcbabcd"
Constraints:
0 <= s.length <= 5 * 104
s
consists of lowercase English letters only.
Related Topics:
String, Rolling Hash, String Matching, Hash Function
Similar Questions:
Find the longest palindrome starting at index 0.
// OJ: https://leetcode.com/problems/shortest-palindrome/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1) ignoring the space taken by the answer
class Solution {
public:
string shortestPalindrome(string s) {
unsigned d = 16777619, h = 0, rh = 0, p = 1, maxLen = 0;
for (int i = 0; i < s.size(); ++i) {
h = h * d + s[i] - 'a';
rh += (s[i] - 'a') * p;
p *= d;
if (h == rh) maxLen = i + 1;
}
return string(rbegin(s), rbegin(s) + s.size() - maxLen) + s;
}
};
// OJ: https://leetcode.com/problems/shortest-palindrome/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
string shortestPalindrome(string s) {
int N = s.size();
string t = "^*";
for (char c : s) {
t += c;
t += '*';
}
t += '$';
vector<int> r(t.size(), 1);
int j = 1, len = 0;
for (int i = 2; i <= 2 * N; ++i) {
int cur = j + r[j] > i ? min(r[2 * j - i], j + r[j] - i) : 1;
while (t[i - cur] == t[i + cur]) ++cur;
if (i + cur > j + r[j]) j = i;
r[i] = cur;
if (i - cur == 0) len = i - 1;
}
return string(rbegin(s), rbegin(s) + N - len) + s;
}
};