Skip to content

Commit 22605ba

Browse files
authored
Update 214-shortest-palindrome.js
1 parent c1dd84a commit 22605ba

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

214-shortest-palindrome.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,37 @@ function getFail(s) {
5050
return table
5151
}
5252

53+
// another
54+
55+
/**
56+
* @param {string} s
57+
* @return {string}
58+
*/
59+
const shortestPalindrome = function(s) {
60+
const tmp = `${s}#${reverse(s)}`
61+
const table = kmp(tmp)
62+
return `${reverse(s.slice(table[table.length - 1]))}${s}`
63+
};
64+
function reverse(str) {
65+
return [...str].reverse().join('')
66+
}
67+
68+
function kmp(s) {
69+
const n = s.length, table = Array(n).fill(0)
70+
let idx = 0
71+
for(let i = 1; i < n; ) {
72+
if(s[i] === s[idx]) {
73+
idx++
74+
table[i] = idx
75+
i++
76+
} else {
77+
if(idx > 0) {
78+
idx = table[idx - 1]
79+
} else {
80+
idx = 0
81+
i++
82+
}
83+
}
84+
}
85+
return table
86+
}

0 commit comments

Comments
 (0)