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;
    }
相关推荐
m0_739312871 小时前
四元数、李群SO(3)/李代数so(3)的作用及应用场景
算法·机器人·自动驾驶
A黄俊辉A2 小时前
【无标题】
java
BestHeaker2 小时前
跨企业接口对接:IQDS / CPK 数据解析与协作避坑指南(五)
java·服务器·前端
artificiali2 小时前
880 第4章多元
人工智能·算法
Felven2 小时前
B. Deja Vu
数据结构·算法
俊昭喜喜里2 小时前
C#中的func<>
java·前端·c#
highreport2 小时前
net报表工具对比:HighReport 与 FastReport
java·c#
小玮看世界2 小时前
[Python]螺旋遍历 vs 最短路径:方向控制类算法的“同源异流”
开发语言·python·算法
月华路2 小时前
《模型不玄学》第14章 标签、损失与样本权重
人工智能·算法·机器学习
黄金龙PLUS2 小时前
SPARKLE置换算法的优缺点
算法·网络安全·密码学·哈希算法·同态加密