您的位置:首页 > 编程语言 > C语言/C++

*leetcode #132 in cpp

2016-06-22 04:14 393 查看
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.

Code:

class Solution {
public:
int minCut(string s) {
int n = s.length();
if(s.empty()) return 0;
vector<vector<bool>> isPal(n,vector<bool>(n,false));
for(int i = 0; i < n; i ++){
isPal[i][i] = true;
for(int j = 0; j < i; j ++){
if( j== i -1){
isPal[j][i] = s[i]==s[j];
}else{
isPal[j][i] = isPal[j+1][i-1] && s[j] == s[i];
}
}
}

if(isPal[0][n-1]) return 0;

vector<int> dp(n,n);//dp[i] = min cut in s[0...i]
for(int i = 0; i < n; i ++){
dp[i] = i;//worst case, s[0...i] has i cuts
if(isPal[0][i]) dp[i] = 0;
else{
int j = 0;
while(j<i){
if(isPal[j+1][i]) dp[i] = min(dp[i], dp[j] + 1);
j++;
}
}

}
return dp[n-1];
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode