Golang | Leetcode Golang题解之第131题分割回文串

题目:

题解:

Go 复制代码
func partition(s string) (ans [][]string) {
    n := len(s)
    f := make([][]int8, n)
    for i := range f {
        f[i] = make([]int8, n)
    }

    // 0 表示尚未搜索,1 表示是回文串,-1 表示不是回文串
    var isPalindrome func(i, j int) int8
    isPalindrome = func(i, j int) int8 {
        if i >= j {
            return 1
        }
        if f[i][j] != 0 {
            return f[i][j]
        }
        f[i][j] = -1
        if s[i] == s[j] {
            f[i][j] = isPalindrome(i+1, j-1)
        }
        return f[i][j]
    }

    splits := []string{}
    var dfs func(int)
    dfs = func(i int) {
        if i == n {
            ans = append(ans, append([]string(nil), splits...))
            return
        }
        for j := i; j < n; j++ {
            if isPalindrome(i, j) > 0 {
                splits = append(splits, s[i:j+1])
                dfs(j + 1)
                splits = splits[:len(splits)-1]
            }
        }
    }
    dfs(0)
    return
}
相关推荐
leoufung1 天前
LeetCode 149: Max Points on a Line - 解题思路详解
算法·leetcode·职场和发展
样例过了就是过了1 天前
LeetCode热题100 最长公共子序列
c++·算法·leetcode·动态规划
样例过了就是过了1 天前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
geovindu1 天前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
开发小程序的之朴1 天前
基于Go语言的企业级CMS系统架构设计与性能分析——以AnQiCMS为例
开发语言·golang·系统架构
Navigator_Z1 天前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
初心未改HD1 天前
Go语言net/http与Web开发:构建高性能HTTP服务
开发语言·golang
如何原谅奋力过但无声1 天前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
leoufung1 天前
LeetCode 42:接雨水 —— 从“矩形法”到双指针的完整思考过程
java·算法·leetcode
memories1981 天前
Go 语言 Channel(管道/通道)
开发语言·后端·golang