LeetCode-热题100:131. 分割回文串

题目描述

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

示例 1:

输入: s = "aab"
输出: [["a","a","b"],["aa","b"]]

示例 2:

输入: s = "a"
输出: [["a"]]

提示:

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

代码及注释

go 复制代码
func partition(s string) [][]string {
    // 初始化结果集和当前路径
    res, path := make([][]string, 0), make([]string, 0)
    
    // 定义深度优先搜索函数
    var dfs func(s string, pos int)
    dfs = func(s string, pos int) {
        // 如果已经遍历到字符串的末尾,将当前路径添加到结果集中
        if pos == len(s) {
            tmp := make([]string, len(path))
            copy(tmp, path)
            res = append(res, tmp)
            return
        }

        // 遍历字符串,查找回文子串
        for i := pos; i < len(s); i++ {
            str := s[pos : i+1]
            // 如果找到回文子串,将其添加到路径中,继续搜索
            if isPalindrome(str) {
                path = append(path, str)
                dfs(s, i+1)
                // 回溯,将当前回文子串从路径中移除
                path = path[:len(path)-1]
            }
        }
    }

    // 开始深度优先搜索
    dfs(s, 0)
    
    // 返回结果集
    return res
}

// 判断字符串是否为回文串
func isPalindrome(s string) bool {
    left, right := 0, len(s)-1
    for left < right {
        if s[left] != s[right] {
            return false
        }
        left++
        right--
    }
    return true
}
相关推荐
CoovallyAIHub1 天前
MSD-DETR:面向机车弹簧检测的可变形注意力Detection Transformer
算法·架构
CoovallyAIHub1 天前
不改权重、不用训练!BEM用背景记忆抑制固定摄像头误检,YOLO/RT-DETR全系有效
算法·架构·github
Struggle_97551 天前
算法知识-从递归入手三维动态规划
算法·动态规划
yuan199971 天前
使用模糊逻辑算法进行路径规划(MATLAB实现)
开发语言·算法·matlab
不才小强1 天前
线性表详解:顺序与链式存储
数据结构·算法
CoovallyAIHub1 天前
上交+阿里 | Interactive ASR:Agent框架做语音识别交互纠错,1轮交互语义错误率降57%
算法·架构·github
Aaron15881 天前
8通道测向系统演示科研套件
人工智能·算法·fpga开发·硬件工程·信息与通信·信号处理·基带工程
计算机安禾1 天前
【数据结构与算法】第42篇:并查集(Disjoint Set Union)
c语言·数据结构·c++·算法·链表·排序算法·深度优先
吃着火锅x唱着歌1 天前
LeetCode 150.逆波兰表达式求值
linux·算法·leetcode
YuanDaima20481 天前
二分查找基础原理与题目说明
开发语言·数据结构·人工智能·笔记·python·算法