1,题目要求
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
给定字符串s,分区s使得分区的每个子字符串都是回文。
返回s的所有可能的回文分区。
2,题目思路
对于这道题,要求找到一个字符串所有的回文的划分结果。
回文不必多说,就是一个字符串的字符是否是对称的。
而对于这道题,我们需要对所有的情况都进行一个判断,因此,使用dfs来对这个字符串进行一个遍历。
遍历这个字符串,检查substr(0,i)是否是回文串。如果是,就递归地利用dfs查找剩下的子串——substr(i+1,length)。直到字符串的尾部为位置。
3,代码实现
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> path;
dfs(0, s, path, res);
return res;
}
private:
void dfs(int index, string &s, vector<string> &path, vector<vector<string>> &res){
if(index == s.size()){
res.push_back(path);
return;
}
for(int i = index;i < s.size();i++){
if(isPalindrome(s, index, i)){
path.push_back(s.substr(index, i - index + 1));
dfs(i+1, s, path, res);
path.pop_back();
}
}
}
bool isPalindrome(string &s, int start, int end){
while(start<=end)
if(s[start++]!=s[end--])
return false;
return true;
}
};