LeetCode:131. 分割回文串

跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:131. 分割回文串

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

示例 1:

输入:s = "aab"

输出:\["a","a","b","aa","b"]

示例 2:

输入:s = "a"

输出:\["a"]

其实这题和前面的组合问题还是类似的,只是这里加了个切割字符串并且判断是否回文的概念,需要注意子串怎么切割,这里是左闭右开的,index~i + 1这个区间的就是子串

java 复制代码
	public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        backtracking(s, 0, new ArrayList<>(), res);
        return res;
    }

    private void backtracking(String s, int index, List<String> path, List<List<String>> res) {
        if (index == s.length()) {
            res.add(new ArrayList(path));
            return;
        }
        for (int i = index; i < s.length(); i++) {
            if (isPalindrome(s, index, i)) {
                path.add(s.substring(index, i + 1));
                backtracking(s, i + 1, path, res);
                path.remove(path.size() - 1);
            }
        }
    }

    private boolean isPalindrome(String s, int start, int end) {
        while (start <= end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
相关推荐
luj_176817 分钟前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
饼饼学习空间智能2 小时前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
Aphelios3802 小时前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽
不可求~2 小时前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
Lam Tang2 小时前
APS 系列文章10
java·代理模式
考虑考虑3 小时前
Excel导入时产生特殊字符处理
java·后端·java ee
蛋先生DX3 小时前
你瘦不下来但大模型可以:量化原理了解一下
深度学习·算法·llm
Scabbards_3 小时前
面试Leetcode - Heap 堆
java·leetcode·面试
程序员清风4 小时前
专业再升级!程序员专属显示器明基RD280UG上手实测!
java·后端·面试