LeetCode:Palindrome Partitioning II
2014-09-03 14:09
363 查看
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.
Round 2:
class Solution {
public:
int minCut(string s) {
vector<int> cuts(s.size(), INT_MAX);
bool isPal[s.size()][s.size()];
cuts[0] = 0;
isPal[0][0] = true;
memset(isPal, 0, sizeof(isPal));
for(int i = 0; i < s.size(); i++)
{
for(int j = 0; j <= i; j++)
{
if((i-j > 2 && s[i] == s[j] && isPal[j+1][i-1]) || (i-j <= 2 && s[i] == s[j]))
{
isPal[j][i] = true;
if(j == 0)
cuts[i] = 0;
else
cuts[i] = std::min(cuts[i], cuts[j-1]+1);
}
}
}
return cuts[s.size()-1];
}
};
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.
class Solution { public: int minCut(string s) { s = '#' + s; vector<int> result(s.size() + 1, INT_MAX); result[0] = -1; bool isPal[s.size()][s.size()]; for(int i = 0; i < s.size(); i++) for(int j = 0; j < s.size(); j++) { isPal[i][j] = false; } for(int i = 1; i < s.size(); i++) { for(int j = 1; j <= i; j++) { if((i - j < 2 && s[i] == s[j]) || ((i - j >= 2) && isPal[j+1][i-1] && s[i] == s[j])) { isPal[j][i] = true; if(j-1 < 0) result[i] = 0; else result[i] = min(result[i], result[j-1] + 1); } } } return result[s.size() - 1]; } };
Round 2:
class Solution {
public:
int minCut(string s) {
vector<int> cuts(s.size(), INT_MAX);
bool isPal[s.size()][s.size()];
cuts[0] = 0;
isPal[0][0] = true;
memset(isPal, 0, sizeof(isPal));
for(int i = 0; i < s.size(); i++)
{
for(int j = 0; j <= i; j++)
{
if((i-j > 2 && s[i] == s[j] && isPal[j+1][i-1]) || (i-j <= 2 && s[i] == s[j]))
{
isPal[j][i] = true;
if(j == 0)
cuts[i] = 0;
else
cuts[i] = std::min(cuts[i], cuts[j-1]+1);
}
}
}
return cuts[s.size()-1];
}
};
相关文章推荐
- [Leetcode]Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- Leetcode237: Palindrome Partitioning II
- Leetcode 132 Palindrome Partitioning II
- Leetcode 132. Palindrome Partitioning II (Hard) (cpp)
- [LeetCode]132 Palindrome Partitioning II
- [Leetcode][python]Palindrome Partitioning/Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- LeetCode之Palindrome Partitioning II
- LeetCode132 Palindrome Partitioning II&I
- Leetcode: Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- LeetCode - Palindrome Partitioning II 题解
- 147_leetcode_Palindrome Partitioning II
- 【leetcode刷题笔记】Palindrome Partitioning II
- leetcode[132]Palindrome Partitioning II