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"]
]
思路:我们从第一个字符开始直到最后一个字符,一旦有可以构造成回文的字符串,继续判断剩下的字符串是否可以构造成回文字符串。直到真个字符串都构造结束,输出构成的方式。使用一个向量记录构成的方式。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool check(string& str,int begin,int end)
{
int i = begin ;
int j = end;
for(;i<=j;i++,j--)
if(str[i] != str[j])
return false;
return true;
}
void helper(string& str,int begin,int end,vector<int>& pos)
{
int i,j,k;
if(begin > end)
{
for(j=0;j<pos.size();j++)
{
cout<<str[j];
if(pos[j] != -1)
{
cout<<",";
pos[j] = -1;
}
}
cout<<endl;
}
for(i= begin;i<=end;i++)
{
if(check(str,begin,i))
{
pos[i] = i-begin+1;
helper(str,i+1,end,pos);
}
}
}
void PalindromePartition(string& str)
{
if(str.length() == 0)
return ;
vector<int> pos(str.length(),-1);
helper(str,0,str.length()-1,pos);
}
int main()
{
string str("aab");
PalindromePartition(str);
system("pause");
return 0;
}
Palindrome Partitioning--LeetCode
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44996133