Skip to content

Commit e41f6a8

Browse files
authored
Update 1745-palindrome-partitioning-iv.js
1 parent c02bc66 commit e41f6a8

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1745-palindrome-partitioning-iv.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,54 @@
1+
/**
2+
* @param {string} s
3+
* @return {boolean}
4+
*/
5+
const checkPartitioning = function(s) {
6+
const map = manacher(s);
7+
return checkPartitioningDfs(map, s, 0);
8+
};
9+
10+
function checkPartitioningDfs(map, word, i, path = []) {
11+
if (path.length > 3) return false;
12+
if (path.length == 3 && path.join('') == word) return true;
13+
let found = false;
14+
const length = map.get(i);
15+
path.push(word.substr(i, length));
16+
found = found || checkPartitioningDfs(map, word, i + length, path);
17+
path.pop();
18+
19+
path.push(word.substr(i, 1));
20+
found = found || checkPartitioningDfs(map, word, i + 1, path);
21+
path.pop();
22+
23+
return found;
24+
}
25+
26+
function manacher(s) {
27+
const t = '^#' + s.split('').join('#') + '#$';
28+
let r = 0;
29+
let c = 0;
30+
let maxC = 0;
31+
const rad = new Array(t.length).fill(0);
32+
for (let i = 1; i < t.length - 1; ++i) {
33+
if (r > i) rad[i] = Math.min(rad[2 * c - i], r - i);
34+
while (t[i - rad[i] - 1] == t[i + rad[i] + 1]) rad[i]++;
35+
if (i + rad[i] > r) {
36+
c = i;
37+
r = i + rad[i];
38+
}
39+
if (rad[c] > rad[maxC]) maxC = c;
40+
}
41+
const ans = new Map();
42+
for (let i = 0; i < rad.length; ++i) {
43+
if (rad[i] > 0) {
44+
ans.set((i - rad[i] - 1) >>> 1, rad[i]);
45+
}
46+
}
47+
return ans;
48+
}
49+
50+
// another
51+
152
/**
253
* @param {string} s
354
* @return {boolean}

0 commit comments

Comments
 (0)