-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0131-palindrome-partitioning.js
More file actions
39 lines (34 loc) · 1.18 KB
/
0131-palindrome-partitioning.js
File metadata and controls
39 lines (34 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Palindrome Partitioning
* Time Complexity: O(N^2 * 2^N)
* Space Complexity: O(N * 2^N)
*/
var partition = function(s) {
const allPartitionResults = [];
const isInputPalindrome = (checkingString) => {
let startPointer = 0;
let endPointer = checkingString.length - 1;
while (startPointer < endPointer) {
if (checkingString[startPointer] !== checkingString[endPointer]) {
return false;
}
startPointer++;
endPointer--;
}
return true;
};
const findPartitions = (currentProcessedParts, remainingSubstring) => {
if (!remainingSubstring.length) {
allPartitionResults.push(currentProcessedParts);
return;
}
for (let splitIndex = 1; splitIndex <= remainingSubstring.length; splitIndex++) {
const candidatePalindrome = remainingSubstring.slice(0, splitIndex);
if (isInputPalindrome(candidatePalindrome)) {
findPartitions([...currentProcessedParts, candidatePalindrome], remainingSubstring.slice(splitIndex));
}
}
};
findPartitions([], s);
return allPartitionResults;
};