Skip to content

Commit fb9d6d1

Browse files
committed
Add solution #131
1 parent d0b15f3 commit fb9d6d1

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy|
9191
125|[Valid Palindrome](./0125-valid-palindrome.js)|Easy|
9292
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
93+
131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium|
9394
133|[Clone Graph](./0133-clone-graph.js)|Medium|
9495
134|[Gas Station](./0134-gas-station.js)|Medium|
9596
135|[Candy](./0135-candy.js)|Hard|
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 131. Palindrome Partitioning
3+
* https://leetcode.com/problems/palindrome-partitioning/
4+
* Difficulty: Medium
5+
*
6+
* Given a string s, partition s such that every substring of the partition
7+
* is a palindrome. Return all possible palindrome partitioning of s.
8+
*/
9+
10+
/**
11+
* @param {string} s
12+
* @return {string[][]}
13+
*/
14+
var partition = function(s) {
15+
return backtrack([], s);
16+
};
17+
18+
function backtrack(order, string, result = []) {
19+
if (!string.length) {
20+
result.push(order);
21+
}
22+
23+
for (let index = 1; index <= string.length; index++) {
24+
const sliced = string.slice(0, index);
25+
if (isPalindrome(sliced)) {
26+
backtrack([...order, sliced], string.slice(index), result);
27+
}
28+
}
29+
30+
return result;
31+
}
32+
33+
function isPalindrome(input) {
34+
let right = input.length - 1;
35+
let left = 0;
36+
37+
while (left < right) {
38+
if (input[left] !== input[right]) {
39+
return false;
40+
}
41+
left++;
42+
right--;
43+
}
44+
45+
return true;
46+
}

0 commit comments

Comments
 (0)