LeetCode hot100-61-G

java 复制代码
131. 分割回文串

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

做不来,官方答案一大坨都不想看,评论区找了个答案跑了一下,感觉还不错,但是自己还是写不出来这种题,后面得做专项总结,回溯包括大部分递归都是直接看答案看过去了,真菜。

https://leetcode.cn/problems/palindrome-partitioning/description/?envType=study-plan-v2\&envId=top-100-liked

C++ MAN

发布于 四川(编辑过)

2023.08.21

java 复制代码
public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        partition(s, 0, 0, new ArrayList<>(), res);
        return res;
  }
public void partition(String s, int start, int end, List<String> tempRes, List<List<String>> res) {
        //如果分隔起点超出了字符串长度,说明已经分隔完,直接将结果返回
        if (start == s.length()) {
            res.add(new ArrayList<>(tempRes));
            return;
        }
        //如果分隔终点超出了字符串,直接返回
        if (end == s.length()) {
            return;
        }
        //当前不进行拆分,直接将end+1
        partition(s, start, end + 1, tempRes, res);
        //当前进行拆分
        String part = s.substring(start, end + 1);
        //是回文字符串,加入到结果中
        if (isPalindrome(part)) {
            tempRes.add(part);
            //start和end更新为分隔部分的下一个字符
            partition(s, end + 1, end + 1, tempRes, res);
            //回溯
            tempRes.remove(tempRes.size() - 1);
        }
    }
    private boolean isPalindrome(String s) {
        int start =0;
        int end = s.length() - 1;
        while (start <= end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
相关推荐
邵奈一19 分钟前
当沉香之乡遇上 Seed-2.1-pro:我用 AI 给村子做了一个数字门面
算法·架构
海天一色y28 分钟前
图像分割全解析:从经典算法到深度学习的原理与实战(Python + MATLAB)
python·深度学习·算法
垆边人似月.1 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
YOLO数据集集合1 小时前
机器学习二分类预测算法组合工具:12种算法、113种组合的批量建模方案8031期
算法·机器学习
longlongzihan1 小时前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode
顶点多余1 小时前
9.24 面试复盘
面试·职场和发展
学术小李2 小时前
cudaMalloc第一个参数为何是指针的指针
算法
kukubuzai2 小时前
二分查找系列一
数据结构·算法·leetcode
老歌老听老掉牙2 小时前
动态规划:从递归到最优决策的算法艺术
算法·动态规划