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;
    }
相关推荐
我家大宝最可爱36 分钟前
动态规划:入门思考篇
算法·动态规划·代理模式
肉夹馍不加青椒1 小时前
第三十三天(信号量)
java·c语言·算法
古译汉书1 小时前
嵌入式-SPI番外之按钮驱动程序的编写-Day15
c语言·stm32·单片机·嵌入式硬件·mcu·算法
测试老哥1 小时前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
快去睡觉~2 小时前
力扣48:旋转矩阵
算法·leetcode·矩阵
卡洛斯(编程版3 小时前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
NAGNIP4 小时前
DeepSeekMoE 架构解析
算法
不喜欢学数学er4 小时前
算法第五十二天:图论part03(第十一章)
算法·深度优先·图论
养成系小王4 小时前
四大常用排序算法
数据结构·算法·排序算法
NAGNIP4 小时前
一文搞懂DeepSeek LLM
算法