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;
    }
相关推荐
十盒半价6 分钟前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七12 分钟前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战21 分钟前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说21 分钟前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
WebInfra22 分钟前
如何在程序中嵌入有大量字符串的 HashMap
算法·设计模式·架构
Wyc7240930 分钟前
SpringBoot
java·spring boot·spring
Bella_chene32 分钟前
IDEA中无法使用JSP内置对象
java·servlet·intellij-idea·jsp
森焱森1 小时前
APM与ChibiOS系统
c语言·单片机·算法·架构·无人机
凯基迪科技1 小时前
exe软件壳的分类----加密保护壳
java
★Orange★1 小时前
Linux Kernel kfifo 实现和巧妙设计
linux·运维·算法