Skip to content

Commit 598d128

Browse files
committed
Add solution #1147
1 parent 3c78455 commit 598d128

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,153 LeetCode solutions in JavaScript
1+
# 1,154 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -901,6 +901,7 @@
901901
1144|[Decrease Elements To Make Array Zigzag](./solutions/1144-decrease-elements-to-make-array-zigzag.js)|Medium|
902902
1145|[Binary Tree Coloring Game](./solutions/1145-binary-tree-coloring-game.js)|Medium|
903903
1146|[Snapshot Array](./solutions/1146-snapshot-array.js)|Medium|
904+
1147|[Longest Chunked Palindrome Decomposition](./solutions/1147-longest-chunked-palindrome-decomposition.js)|Hard|
904905
1161|[Maximum Level Sum of a Binary Tree](./solutions/1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
905906
1189|[Maximum Number of Balloons](./solutions/1189-maximum-number-of-balloons.js)|Easy|
906907
1200|[Minimum Absolute Difference](./solutions/1200-minimum-absolute-difference.js)|Easy|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 1147. Longest Chunked Palindrome Decomposition
3+
* https://leetcode.com/problems/longest-chunked-palindrome-decomposition/
4+
* Difficulty: Hard
5+
*
6+
* You are given a string text. You should split it to k substrings (subtext1,
7+
* subtext2, ..., subtextk) such that:
8+
* - subtexti is a non-empty string.
9+
* - The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2
10+
* + ... + subtextk == text).
11+
* - subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).
12+
*
13+
* Return the largest possible value of k.
14+
*/
15+
16+
/**
17+
* @param {string} text
18+
* @return {number}
19+
*/
20+
var longestDecomposition = function(text) {
21+
return decompose(0, text.length - 1);
22+
23+
function decompose(start, end) {
24+
if (start > end) return 0;
25+
if (start === end) return 1;
26+
27+
const left = start;
28+
const right = end;
29+
let chunkSize = 0;
30+
31+
while (left + chunkSize < right - chunkSize) {
32+
chunkSize++;
33+
if (text.slice(left, left + chunkSize) === text.slice(right - chunkSize + 1, right + 1)) {
34+
return 2 + decompose(left + chunkSize, right - chunkSize);
35+
}
36+
}
37+
38+
return 1;
39+
}
40+
};

0 commit comments

Comments
 (0)