Skip to content

Commit 323504b

Browse files
authored
Update 214-shortest-palindrome.js
1 parent 105a8dc commit 323504b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

214-shortest-palindrome.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,42 @@ const shortestPalindrome = function(s) {
1111
let suffix = s.substring(j);
1212
return suffix.split('').reverse().join('') + shortestPalindrome(s.substring(0, j)) + suffix;
1313
};
14+
15+
// another
16+
17+
/**
18+
* @param {string} s
19+
* @return {string}
20+
*/
21+
const shortestPalindrome = function (s) {
22+
const tmp = s + '#' + s.split('').reverse().join('')
23+
const fail = getFail(tmp)
24+
return (
25+
s
26+
.split('')
27+
.slice(fail[fail.length - 1])
28+
.reverse()
29+
.join('') + s
30+
)
31+
}
32+
33+
function getFail(s) {
34+
const n = s.length
35+
const table = new Array(n).fill(0)
36+
let index = 0
37+
for (let i = 1; i < n; ) {
38+
if (s.charAt(index) === s.charAt(i)) {
39+
table[i] = ++index
40+
i++
41+
} else {
42+
if (index > 0) {
43+
index = table[index - 1]
44+
} else {
45+
index = 0
46+
i++
47+
}
48+
}
49+
}
50+
return table
51+
}
52+

0 commit comments

Comments
 (0)