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"]
]
思路:
题目要求求所有可能拆分成回文数的情况,那么肯定都需要遍历到,对于每一个字符串都要分别判断是不是回文数,需要一个判断回文字符串的函数,还需要一个DFS函数来递归。
递归时的终止条件是start值等于字符串长度。比如abcd的递归顺序是a-b-c-d-cd-bc-bcd-ab-abc-abcd
var partition = function(s) {
function isPalindrome(s, start, end) {
while (start < end) {
if (s[start] != s[end]) return false;
++start;
--end;
}
return true;
}
function partitionDFS(s, start, out, res) {
if (start == s.length) {
var tmp=out.concat();
res.push(tmp);
return;
}
for (var i = start; i < s.length; i++) {
if (isPalindrome(s, start, i)) {
out.push(s.substr(start, i - start + 1));
partitionDFS(s, i + 1, out, res);
out.pop();
}
}
}
var res = [];
var out = [];
partitionDFS(s, 0, out, res);
return res;
};
网友评论