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
}
相关推荐
hhzz17 分钟前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_1 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI1 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet1 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件2 小时前
银行客户流失预测(Python 完整实战)
算法
邪神与厨二病2 小时前
牛客周赛 Round 153
python·算法
qizayaoshuap4 小时前
# ❌ 井字棋 — 鸿蒙ArkTS Minimax AI算法与博弈系统设计
人工智能·算法·华为·harmonyos
qq_452396234 小时前
第二篇:《Go 开发环境搭建:SDK、IDE、Module 与 Hello World》
开发语言·ide·golang
皓月斯语5 小时前
B3842 [GESP202306 三级] 春游 题解
数据结构·c++·算法·题解
atunet5 小时前
树状结构在查询优化中的作用与实现细节7
算法