*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 =
Return
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];
}
};
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.
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];
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解