题解 | #所有的回文子串I#
所有的回文子串I
https://www.nowcoder.com/practice/37fd2d1996c6416fa76e1aa46e352141
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串二维数组
*/
function partition(str) {
let res = []; // 存储所有分割方案
let path = []; // 存储当前分割方案
function backTrack(s, start) {
if (start >= s.length) {
res.push([...path]); // 将当前分割方案加入结果集
return;
}
for (let i = start; i < s.length; i++) {
let subStr = s.slice(start, i + 1); // 获取从[start, i]的子串
if (isReverse(subStr)) {
// 如果子串是回文串
path.push(subStr); // 将子串加入当前分割方案
} else {
continue; // 如果不是回文串,则跳过当前子串
}
backTrack(s, i + 1); // 继续向后搜索剩余的子串
path.pop(); // 回溯,将当前子串移出当前分割方案
}
}
backTrack(str, 0); // 从字符串的起始位置开始回溯搜索
return res; // 返回所有分割方案
}
function isReverse(s) {
return [...s].reverse().join("") === s; // 判断字符串是否为回文串
}
module.exports = {
partition: partition,
};