[LeetCode] Palindrome Partitioning II

132. Palindrome Partitioning II

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minCut(string s) {
int n = s.length();
vector<vector<bool>> palindrome(n,vector<bool>(n, false));
vector<int> dp(n);

for(int i = 0; i < n; i++) {
int mi = i;
for(int j = 0; j <= i; j++) {
if(s[j] == s[i] and (j + 1 > i - 1 or palindrome[j+1][i-1])) {
palindrome[j][i] = true;
mi = min(mi, (j == 0 ? 0 : dp[j-1] + 1));
}
}
dp[i] = mi;
}

return dp.back();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/23/PS/LeetCode/palindrome-partitioning-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.