Skip to content

Commit c1dd84a

Browse files
authored
Create 1960-maximum-product-of-the-length-of-two-palindromic-substrings.js
1 parent 80552c5 commit c1dd84a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
const maxProduct = function (s) {
6+
const t1 = helper(s),
7+
t2 = helper(reverse(s))
8+
let res = 0
9+
for (let n = s.length, i = 0, j = n - 2; i < n - 1; ++i, --j)
10+
res = Math.max(res, t1[i] * t2[j])
11+
12+
return res
13+
}
14+
function reverse(s) {
15+
return [...s].reverse().join('')
16+
}
17+
function helper(s) {
18+
const man = manachers(s).filter(
19+
(e, i, ar) => i >= 2 && i < ar.length - 2 && i % 2 === 0
20+
)
21+
const n = s.length,
22+
{ max } = Math
23+
const ints = man.map((e, i) => [i - ~~(e / 2), i + ~~(e / 2)])
24+
const arr = Array(n).fill(0)
25+
for (const [a, b] of ints) {
26+
arr[b] = max(arr[b], b - a + 1)
27+
}
28+
for (let i = n - 2; i >= 0; i--) {
29+
arr[i] = max(arr[i], arr[i + 1] - 2)
30+
}
31+
let tmp = 0
32+
for (let i = 0; i < n; i++) {
33+
if (arr[i] > tmp) {
34+
tmp = arr[i]
35+
} else arr[i] = tmp
36+
}
37+
return arr
38+
}
39+
function manachers(s) {
40+
const str = `@#${s.split('').join('#')}#$`
41+
const arr = Array(str.length).fill(0)
42+
43+
let center = 0,
44+
right = 0
45+
for (let i = 1, n = str.length; i < n - 1; i++) {
46+
if (i < right) {
47+
arr[i] = Math.min(right - i, arr[2 * center - i])
48+
}
49+
while (str[i + arr[i] + 1] === str[i - arr[i] - 1]) {
50+
arr[i] += 1
51+
}
52+
if (i + arr[i] > right) {
53+
center = i
54+
right = i + arr[i]
55+
}
56+
}
57+
58+
return arr
59+
}

0 commit comments

Comments
 (0)