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;
    }
相关推荐
88号技师2 分钟前
2025年11月一区SCI-壁虎优化算法Gekko Japonicus Algorithm-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
RATi GORI4 分钟前
Spring Boot 整合 Keycloak
java·spring boot·后端
吴梓穆5 分钟前
UE5 c++ 模板函数
java·c++·ue5
她说..6 分钟前
Spring单例Bean线程安全问题 深度解析
java·后端·安全·spring·springboot
Seven977 分钟前
MVC快速入门
java
吴梓穆9 分钟前
UE5 c++ 暴露变量和方法给蓝图
java·c++·ue5
浅念-10 分钟前
LeetCode 双指针题型 C++ 解题整理
开发语言·数据结构·c++·笔记·算法·leetcode·职场和发展
风向决定发型丶11 分钟前
Java 线程池 vs Go GMP
java·开发语言·golang
zzb158023 分钟前
Agent案例-智能文档问答助手
java·人工智能·笔记·python
Mr_Xuhhh25 分钟前
LeetCode hot 100(C++版本)
c++·leetcode·哈希算法