-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathshortest-palindrome.js
51 lines (46 loc) · 1004 Bytes
/
shortest-palindrome.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Shortest Palindrome
*
* Given a string S, you are 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".
*/
/**
* KMP algorithm to get the longest prefix and suffix count
*
* @param {string} s
* @return {number[]}
*/
const getLPS = s => {
const lps = Array(s.length).fill(0);
let i = 1;
let len = 0;
while (i < s.length) {
if (s[i] === s[len]) {
lps[i++] = ++len;
} else if (len === 0) {
lps[i++] = 0;
} else {
len = lps[len - 1];
}
}
return lps;
};
/**
* @param {string} s
* @return {string}
*/
const shortestPalindrome = s => {
const r = s
.split('')
.reverse()
.join('');
const lps = getLPS(s + '|' + r);
return r.substring(0, r.length - lps[lps.length - 1]) + s;
};
export default shortestPalindrome;