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;
    }
相关推荐
NE_STOP12 小时前
Vide Coding--AI编程工具的选择
java
通信小呆呆12 小时前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
码云数智-园园12 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆12 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
benben04412 小时前
强化学习之DQN算法族(基于gymnasium开发)
算法
小宇宙Zz13 小时前
Maven依赖冲突
java·服务器·maven
swordbob13 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯13 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网13 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记