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.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
Code:
<span style="font-size:14px;">class Solution {
public:
int minCut(string s) {
const int length = s.size();
if (length == 0 || length == 1) return 0;
bool **dp = new bool *[length];
for (int i = 0; i < length; ++i) {
dp[i] = new bool[length];
memset(dp[i], false, sizeof(bool)*length);
dp[i][i] = true;
}
int cuts[length];
cuts[0] = 0;
for (int i = 1; i < length; ++i) {
cuts[i] = cuts[i-1]+1;
for (int j = 0; j < i; ++j) {
if (s[i] == s[j] && (i-j<2 || dp[j+1][i-1])) {
dp[j][i] = true;
if (j == 0) cuts[i] = 0;
else cuts[i] = min(cuts[i], cuts[j-1]+1);
}
}
}
for (int i = 0; i < length; ++i)
delete [] dp[i];
delete [] dp;
return cuts[length-1];
}
};</span>