Skip to content

Commit edbe624

Browse files
committed
Add solution #132
1 parent b07d573 commit edbe624

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@
136136
129|[Sum Root to Leaf Numbers](./0129-sum-root-to-leaf-numbers.js)|Medium|
137137
130|[Surrounded Regions](./0130-surrounded-regions.js)|Medium|
138138
131|[Palindrome Partitioning](./0131-palindrome-partitioning.js)|Medium|
139+
132|[Palindrome Partitioning II](./0132-palindrome-partitioning-ii.js)|Hard|
139140
133|[Clone Graph](./0133-clone-graph.js)|Medium|
140141
134|[Gas Station](./0134-gas-station.js)|Medium|
141142
135|[Candy](./0135-candy.js)|Hard|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 132. Palindrome Partitioning II
3+
* https://leetcode.com/problems/palindrome-partitioning-ii/
4+
* Difficulty: Hard
5+
*
6+
* Given a string s, partition s such that every substring of the partition is a palindrome.
7+
*
8+
* Return the minimum cuts needed for a palindrome partitioning of s.
9+
*/
10+
11+
/**
12+
* @param {string} s
13+
* @return {number}
14+
*/
15+
var minCut = function(s) {
16+
const isPalindrome = new Array(s.length).fill().map(() => new Array(s.length).fill(false));
17+
const partitions = new Array(s.length).fill(0);
18+
19+
for (let i = 0; i < s.length; i++) {
20+
let offset = i;
21+
for (let j = 0; j <= i; j++) {
22+
if (s[j] === s[i] && (i - j <= 1 || isPalindrome[j + 1][i - 1])) {
23+
isPalindrome[j][i] = true;
24+
offset = j === 0 ? 0 : Math.min(offset, partitions[j - 1] + 1);
25+
}
26+
}
27+
partitions[i] = offset;
28+
}
29+
30+
return partitions[s.length - 1];
31+
};

0 commit comments

Comments
 (0)