您的位置:首页 > 其它

LeetCode-Palindrome Partitioning II

2014-07-30 13:36 375 查看
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.
Solution:
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息