-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindrome-partitioning.js
More file actions
65 lines (53 loc) · 1.38 KB
/
palindrome-partitioning.js
File metadata and controls
65 lines (53 loc) · 1.38 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Problem: Palindrome Partitioning
* Link: https://leetcode.com/problems/palindrome-partitioning/
* Difficulty: Medium
*
* Partition string so every substring is a palindrome.
*
* Example: "aab" => [["a","a","b"],["aa","b"]]
*
* Time Complexity: O(n * 2^n)
* Space Complexity: O(n)
*/
// JavaScript Solution - Backtracking
function partition(s) {
const result = [];
function backtrack(start, current) {
if (start === s.length) { result.push([...current]); return; }
for (let end = start; end < s.length; end++) {
if (isPalindrome(s, start, end)) {
current.push(s.substring(start, end + 1));
backtrack(end + 1, current);
current.pop();
}
}
}
backtrack(0, []);
return result;
}
function isPalindrome(s, l, r) {
while (l < r) {
if (s[l++] !== s[r--]) return false;
}
return true;
}
module.exports = partition;
/* Python Solution:
def partition(s):
result = []
def is_palindrome(sub):
return sub == sub[::-1]
def backtrack(start, current):
if start == len(s):
result.append(list(current))
return
for end in range(start, len(s)):
sub = s[start:end+1]
if is_palindrome(sub):
current.append(sub)
backtrack(end + 1, current)
current.pop()
backtrack(0, [])
return result
*/