[LeetCode] 065: Palindrome Partitioning II

来源:互联网 发布:js点击按钮让日期增加 编辑:程序博客网 时间:2024/06/14 22:30
[Problem]

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]

class Solution {
public:
int minCut(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(s.size() <= 1)return 0;

// initial
int dp[s.size()+1];
memset(dp, -1, sizeof(dp));
bool mark[s.size()][s.size()];
memset(mark, 0, sizeof(mark));

// dp
for(int i = s.size()-1; i >= 0; --i){
dp[i] = s.size();
for(int j = i; j < s.size(); ++j){
if(s[i] == s[j] && (j - i < 2 || mark[i+1][j-1])){
mark[i][j] = true;
dp[i] = min(dp[i], dp[j+1] + 1);
}
}
}
return dp[0];
}
};

说明:版权所有,转载请注明出处。Coder007的博客