分割回文串
问题
给你一个字符串 s
,请你将 s
分割成一些 子串,使每个子串都是 回文串 。返回 s
所有可能的分割方案。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a"
输出:[["a"]]
答案
js
function ishw(s,l,r){
for(let i=l,j=r;i<j;i++,j--){
if(s[i]!=s[j]) return false;
}
return true;
}
var partition = function(s) {
let res=[];
let path=[];
let dfs=(index)=>{
if(index>=s.length){
res.push([...path]);
return;
}
for(let i=index;i<s.length;i++){
if(!ishw(s,index,i)) continue;
path.push(s.slice(index,i+1));
dfs(i+1);
path.pop();
}
}
dfs(0);
return res;
};