您的位置:首页 > 其它

[Leetcode] #131#132 Palindrome Partitioning I & II

2017-02-16 21:22 344 查看

Discription:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = 
"aab"
,

Return
[
["aa","b"],
["a","a","b"]
]

Solution:

bool isPalindrome(const string &s, int begin, int end){
while (begin < end){
if (s[begin] != s[end])
return false;
begin++;
end--;
}
return true;
}

void partition(string s, vector<vector<string>> &result, vector<string> &temp,int begin,int len) {
if (begin >= len){
result.push_back(temp);
return;
}
for (int i = begin; i < len; i++){
if (!isPalindrome(s, begin, i))
continue;
temp.push_back(s.substr(begin, i - begin + 1));
partition(s, result, temp, i + 1, len);
temp.pop_back();
}
}

vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> temp;
partition(s, result, temp, 0, s.size());
return result;
}


Discription:

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:

//超时
bool isPalindrome(const string &s, int begin, int end){
while (begin < end){
if (s[begin] != s[end])
return false;
begin++;
end--;
}
return true;
}

void minCut(string s, int &minc,int begin,int len,int temp) { //aaabaa
if (begin >= len){
if (temp < minc)
minc = temp;
return;
}
for (int i = begin; i < len; i++){
if (!isPalindrome(s, begin, i))
continue;
if (i != len-1)
temp += 1;
minCut(s, minc, i + 1, len, temp);
if (i != len - 1)
temp -= 1;
}
}

int minCut(string s) {
int minc = s.size() - 1;
minCut(s, minc, 0, s.size(), 0);
return minc;
}
//方法二 动态规划
int minCut(string s) {
int size = s.size();
if (size == 0){
return 0;
}
vector<vector<bool>> isPal(size, vector<bool>(size));
vector<int> cut(size);
for (int i = 0; i < size; ++i){
cut[i] = i;
for (int j = 0; j <= i; ++j){
if (s[j] == s[i] && (i - j <= 1 || isPal[j + 1][i - 1])){
isPal[j][i] = true;
if (j == 0){
cut[i] = 0;
}
else{
cut[i] = min(cut[i], cut[j - 1] + 1);
}
}
}
}
return cut[size - 1];
}

GitHub-Leetcode:https://github.com/wenwu313/LeetCode

参考:http://www.2cto.com/kf/201503/379759.html

            https://leetcode.com/problems/palindrome-partitioning-ii/?tab=Solutions
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: