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 =
Return
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>
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s =
"aab",
Return
1since 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>
相关文章推荐
- [Leetcode][JAVA] Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- LeetCode_Palindrome Partitioning II
- LeetCode: Palindrome Partitioning II [132]
- 【LeetCode】Palindrome Partitioning II
- Leetcode: Palindrome Partitioning II
- Palindrome Partitioning II Leetcode
- [LeetCode] Palindrome Partitioning II
- Leetcode_palindrome-partitioning-ii
- Leetcode:Palindrome Partitioning II
- 【LeetCode】Palindrome Partitioning II
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- LeetCode132 Palindrome Partitioning II
- LeetCode Palindrome Partitioning II(***)
- LeetCode132 Palindrome Partitioning II&I
- [leetcode 132] Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- 【LeetCode】Palindrome Partitioning I&II
- [leetcode]Palindrome Partitioning II
- LeetCode - Palindrome Partitioning II