Problem
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 * 10^4
s
consists of lowercase English letters only.
Solution
/**
* @param {string} s
* @return {string}
*/
var shortestPalindrome = function(s) {
const tmp = `${s}#${reverse(s)}`
const table = kmp(tmp)
return `${reverse(s.slice(table[table.length - 1]))}${s}`
};
function reverse(str) {
return [...str].reverse().join('')
}
function kmp(s) {
const n = s.length, table = Array(n).fill(0)
let idx = 0
for(let i = 1; i < n; ) {
if(s[i] === s[idx]) {
idx++
table[i] = idx
i++
} else {
if(idx > 0) {
idx = table[idx - 1]
} else {
idx = 0
i++
}
}
}
return table
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).