【Leetcode】Palindrome Partitioning
2013-11-28 22:07
85 查看
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 =
Return
题意:将字符串分解为众多回文,然后返回。
用递归求解,详细解答见下文
class Solution {
public:
vector<vector<string>> partition(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<string> v;
vector<vector<string>> res;
if(s=="")
{
v.push_back("");
res.push_back(v);
return res;
}
int length=s.size();
recursive(s,0,v,res);
return res;
}
void recursive(string s,int start,vector<string> v,vector<vector<string>> &res)
{
if(start==s.length())
res.push_back(v);
for(int i=start;i<s.length();i++)
{
if(IsPalindrome(s.substr(start,i-start+1)))
{
v.push_back(s.substr(start,i-start+1));
recursive(s,i+1,v,res);
v.pop_back();
}
}
}
bool IsPalindrome(string s)
{
if(s=="")
return true;
int length=s.size();
for(int i=0,j=length-1;i++,j--;i<=j)
{
if(s[i]!=s[j])
return false;
}
return true;
}
};
Return all possible palindrome partitioning of s.
For example, given s =
"aab",
Return
[ ["aa","b"], ["a","a","b"] ]
题意:将字符串分解为众多回文,然后返回。
用递归求解,详细解答见下文
class Solution {
public:
vector<vector<string>> partition(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<string> v;
vector<vector<string>> res;
if(s=="")
{
v.push_back("");
res.push_back(v);
return res;
}
int length=s.size();
recursive(s,0,v,res);
return res;
}
void recursive(string s,int start,vector<string> v,vector<vector<string>> &res)
{
if(start==s.length())
res.push_back(v);
for(int i=start;i<s.length();i++)
{
if(IsPalindrome(s.substr(start,i-start+1)))
{
v.push_back(s.substr(start,i-start+1));
recursive(s,i+1,v,res);
v.pop_back();
}
}
}
bool IsPalindrome(string s)
{
if(s=="")
return true;
int length=s.size();
for(int i=0,j=length-1;i++,j--;i<=j)
{
if(s[i]!=s[j])
return false;
}
return true;
}
};
相关文章推荐
- [LeetCode]Trapping Rain Water
- LeetCode(13) RomanToInteger
- Recover Binary Search Tree -- LeetCode
- leetcode 之 Two Sum 解题思路
- [LeetCode]Sort List
- leetcode[125] Valid Palindrome
- 83. Remove Duplicates from Sorted List Leetcode Python
- leetcode_36_validsudoku
- leetcode 第89题 Gray Code
- [LeetCode][Java] Jump Game
- Leetcode: Happy Number
- LeetCode-Valid Anagram
- LeetCode Longest Substring Without Repeating Characters
- [LeetCode 088] Merge Sorted Array
- leetcode 2 Add Two Numbers
- Leetcode 326. Power of Three
- LeetCode-233.Number of Digit One
- (LeetCode)Linked List Cycle --- 判断循环链表
- [leetcode] 438. Find All Anagrams in a String 解题报告
- Leetcode 90. Subsets II