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;
    }
相关推荐
小妖6661 分钟前
力扣(LeetCode)- 60. 排列序列
算法·leetcode·职场和发展
im_AMBER4 分钟前
Leetcode 70 好数对的数目 | 与对应负数同时存在的最大正整数
数据结构·笔记·学习·算法·leetcode
小妖6664 分钟前
力扣(LeetCode)- 74. 搜索二维矩阵
算法·leetcode·矩阵
天一生水water5 分钟前
Eclipse数值模拟软件详细介绍(油藏开发的“工业级仿真引擎”)
java·数学建模·eclipse
Liangwei Lin6 分钟前
洛谷 U311289 矩阵距离
线性代数·算法·矩阵
谷粒.2 小时前
Cypress vs Playwright vs Selenium:现代Web自动化测试框架深度评测
java·前端·网络·人工智能·python·selenium·测试工具
Dev7z3 小时前
基于MATLAB数学形态学的边缘检测算法仿真实现
算法·计算机视觉·matlab
uzong6 小时前
程序员从大厂回重庆工作一年
java·后端·面试
kyle~6 小时前
C++---value_type 解决泛型编程中的类型信息获取问题
java·开发语言·c++
开心香辣派小星10 小时前
23种设计模式-15解释器模式
java·设计模式·解释器模式