[leetcode] 131. Palindrome Partitioning
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
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:
Output:
[
["aa","b"],
["a","a","b"]
]
分析
题目的意思是:给定一个字符串s,然后分解成若干个字串,使得每个字串都是回文子串,返回所有可能的形式。
- 如果是输出所有可能的状态的话,就要用到深度优先搜索,截取一个子串,然后判断是否为回文子串,如果是,加入path表中,然后深度继续寻找。
- 常规解法,一定要会。
代码
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> out;
dfs(s,0,out,res);
return res;
}
void dfs(string s,int start,vector<string> &out,vector<vector<string>>&res){
if(start==s.size()){
res.push_back(out);
return;
}
for(int i=start;i<s.length();i++){
if(isPalindrome(s,start,i)){
out.push_back(s.substr(start,i-start+1));
dfs(s,i+1,out,res);
out.pop_back();
}
}
}
bool isPalindrome(string s,int start,int end){
while(start<end){
if(s[start]!=s[end]){
return false;
}
start++;
end--;
}
return true;
}
};
参考文献
[编程题]palindrome-partitioning[LeetCode] Palindrome Partitioning 拆分回文串