您的位置:首页 > 其它

【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 = 
"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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息