【算法】分割回文串

难度:中等

题目:

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是

回文串。返回 s 所有可能的分割方案。

示例 1:

输入:s = "aab"

输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"

输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

解题思路:

使用回溯结合简单的回文检测来解决

  1. 定义辅助函数 isPalindrome:
  • 这个函数用于判断一个字符串是否为回文串。
  • 使用两个指针分别从字符串的头部和尾部向中心移动并比较字符是否相等。
  1. 定义递归函数 partition:
  • 参数包括:
    ■ s: 原始输入字符串。
    ■ start: 当前处理的子串起始位置。
    ■ path: 用于存储当前递归路径上的回文子串。
    ■ result: 最终结果数组,用于收集所有满足条件的分割方案。
  • 终止条件:当 start 等于字符串长度时,将 path 加入到结果数组 result 中。
  • 递归逻辑:
    • 遍历从 start 到字符串末尾的所有位置 i。
    • 如果从 start 到 i 的子串是回文串,则将其加入到 path 中。
    • 对剩余的字符串(从 i+1 开始)继续执行相同的操作。
    • 在递归结束后,从 path 中移除刚刚添加的子串,进行回溯。
  1. 调用 partition 函数:
  • 在主函数 partitionPalindromes 中,直接调用 partition 函数,无需额外参数,因为默认值已经设置好。

JavaScript 实现

javascript 复制代码
// 判断是不是回文串
function isPalindrome(str) {
    let left = 0, right = str.length - 1;
    while (left < right) {
        if (str[left] !== str[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// s是原始字符串   start: 当前处理的子串起始位置。path: 用于存储当前递归路径上的回文子串。result: 最终结果数组,用于收集所有满足条件的分割方案。
function partition(s, start = 0, path = [], result = null) {
    if (result === null) {
        result = [];
    }
    
    if (start === s.length) {
        result.push([...path]);
        return result;
    }
    
    for (let i = start; i < s.length; i++) {
        if (isPalindrome(s.slice(start, i + 1))) {
            path.push(s.slice(start, i + 1));
            partition(s, i + 1, path, result);
            path.pop(); // 回溯
        }
    }
    return result;
}

function partitionPalindromes(s) {
    return partition(s);
}

// 测试用例
// const testString = "aab";
// const result = partitionPalindromes(testString);
// console.log(result);
相关推荐
Rubisco..22 分钟前
牛客周赛 Round 111
数据结构·c++·算法
兮山与27 分钟前
算法8.0
算法
高山上有一只小老虎30 分钟前
杨辉三角的变形
java·算法
Swift社区37 分钟前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
hz_zhangrl38 分钟前
CCF-GESP 等级考试 2025年9月认证C++四级真题解析
开发语言·c++·算法·程序设计·gesp·c++四级·gesp2025年9月
少许极端1 小时前
算法奇妙屋(六)-哈希表
java·数据结构·算法·哈希算法·散列表·排序
羊羊小栈1 小时前
基于「多模态大模型 + BGE向量检索增强RAG」的新能源汽车故障诊断智能问答系统(vue+flask+AI算法)
vue.js·人工智能·算法·flask·汽车·毕业设计·大作业
Da Da 泓1 小时前
shellSort
java·数据结构·学习·算法·排序算法
2013编程爱好者1 小时前
计算时间复杂度
c++·算法·排序算法
巴里巴气1 小时前
第15题 三数之和
数据结构·算法·leetcode