Skip to content

Commit d641735

Browse files
Add Palindrome Partitioning algorithm
Implement palindrome partitioning algorithm to find all possible palindromic substrings of a given string.
1 parent 08d8c6b commit d641735

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Palindrome Partitioning Algorithm
3+
* Given a string, find all possible ways to partition it into palindromic substrings
4+
*/
5+
6+
function isPalindrome(s, left, right) {
7+
while (left < right) {
8+
if (s[left] !== s[right]) return false;
9+
left++;
10+
right--;
11+
}
12+
return true;
13+
}
14+
15+
function partition(s) {
16+
const result = [];
17+
const current = [];
18+
19+
function backtrack(start) {
20+
if (start === s.length) {
21+
result.push([...current]);
22+
return;
23+
}
24+
25+
for (let end = start; end < s.length; end++) {
26+
if (isPalindrome(s, start, end)) {
27+
current.push(s.substring(start, end + 1));
28+
backtrack(end + 1);
29+
current.pop();
30+
}
31+
}
32+
}
33+
34+
backtrack(0);
35+
return result;
36+
}
37+
38+
export { partition };

0 commit comments

Comments
 (0)