您的位置:首页 > 其它

LeetCode(Palindrome Partitioning) 将字符串分割成回文字符串

2014-04-08 10:51 411 查看
题目要求:

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> > ans;
//判断是不是回文
bool IsPalindrome(const string& str, int start, int end)
{
if (start == end) {
return true;
}
while (start < end) {
if(str[start] != str[end])
return false;
++start;
--end;
}
return true;
}

void RecursivePartiton(string& s, int start, vector<string>& par)
{
if(start == s.size())
{
ans.push_back(par);
return;
}
for(size_t i = start; i < s.size(); ++i)
{
//如果start 到 i是回文,则将其分割,从下个位置i+1起继续递归分割
if (IsPalindrome(s, start, i)) {
par.push_back(s.substr(start, i - start + 1));
RecursivePartiton(s, i + 1, par);
par.pop_back();//递归回溯
}
}

}

vector<vector<string> > partition(string s) {
vector<string> par;
par.clear();
ans.clear();
RecursivePartiton(s, 0, par);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: