Skip to content

Commit 9fcda96

Browse files
authored
Create Manacher.js
1 parent 2b8e4c5 commit 9fcda96

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/Manacher.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// https://segmentfault.com/a/1190000003914228
2+
function manacher(s) {
3+
// Preprocess
4+
s = '#' + s.split('').join('#') + '#';
5+
6+
let RL = new Array(s.length).fill(0);
7+
let MaxRight = 0;
8+
let pos = 0;
9+
let MaxLen = 0;
10+
11+
for (let i = 0; i < s.length; i++) {
12+
if (i < MaxRight) {
13+
RL[i] = Math.min(RL[2 * pos - i], MaxRight - i);
14+
} else {
15+
RL[i] = 1;
16+
}
17+
// Try to expand, taking care of boundaries
18+
while (i - RL[i] >= 0 && i + RL[i] < s.length && s[i - RL[i]] === s[i + RL[i]]) {
19+
RL[i]++;
20+
}
21+
// Update MaxRight and pos
22+
if (RL[i] + i - 1 > MaxRight) {
23+
MaxRight = RL[i] + i - 1;
24+
pos = i;
25+
}
26+
// Update the length of the longest palindromic substring
27+
MaxLen = Math.max(MaxLen, RL[i]);
28+
}
29+
return MaxLen - 1;
30+
}
31+

0 commit comments

Comments
 (0)