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.
T:
DP. Define cutnum[i] is the number of minimum cuts of s.substr(0, i), then
cutnum[i] = min(cutnum[j] + 1), for 0<j<i and s.substr(j, i-j) is a palindrome.
We also need to consider when j==0, if s.substr(0, i) is apalindrome, then cutnum[i] is 0. Also, cutnum[i] is initialized as i-1.
We need a 2D array pair[i][j] to remember whether s.substr(i, j-i+1) is a palindrome.
A:
class Solution {
public:
int minCut(string s) {
int len = s.size();
if(len == 0) {
return 0;
}
vector< int > cutnum(len+1);
bool pair[len][len];
for(int i=1; i <= len; i++) {
cutnum[i] = i-1;
}
cutnum[0] = 0;
for(int i=0; i < len; i++) {
for(int j=0; j < len; j++) {
pair[i][j] = false;
}
}
for(int i=0; i < len; i++) {
for(int j=0; j <= i; j++) {
if(s[i] == s[j] && (i-j < 2 || pair[j+1][i-1])) {
pair[j][i] = true;
cutnum[i+1] = min(cutnum[i+1], cutnum[j] + ((j==0)?0:1));
}
}
}
return cutnum[len];
}
};
No comments:
Post a Comment