leetcode-分割回文串

给你一个字符串 s,请你将 s 分割成一些 子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

示例 1:

输入:s = "aab"

输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"

输出:[["a"]]

提示:

1 <= s.length <= 16

s 仅由小写英文字母组成

思路 :枚举分割的位置。判断分割后的字符串是否为回文串,是就保存当前字符串,继续分割剩下的字符串。
代码

c 复制代码
class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        dfs(s, new ArrayList<String>(),res);
        return res;
    }

    public void dfs(String s,List<String> temp, List<List<String>> res){
        if(s.isEmpty()){
            res.add(new ArrayList<>(temp));
            return;
        }

        // 枚举分割位置
        for(int i = 1;i<=s.length();i++){
            String t = s.substring(0,i);
            if(isHuiWen(t)){
                temp.add(t);
                dfs(s.substring(i),temp,res);
                temp.remove(temp.size()-1);
            }
        }

    }
    public boolean isHuiWen(String a){
        if(a.isEmpty()){
            return false;
        }
        int left = 0;
        int right = a.length()-1;
        while(left<right){
            if(a.charAt(left)!=a.charAt(right)){
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
相关推荐
小比特_蓝光2 分钟前
算法篇二----二分查找
java·数据结构·算法
田梓燊17 分钟前
leetcode 56
java·算法·leetcode
仍然.40 分钟前
多线程---阻塞队列收尾和线程池
java·开发语言·算法
_深海凉_40 分钟前
LeetCode热题100-最长公共前缀
算法·leetcode·职场和发展
郝学胜-神的一滴40 分钟前
PyTorch自动微分核心解析:从原理到实战实现权重更新
人工智能·pytorch·python·深度学习·算法·机器学习
会编程的土豆1 小时前
【数据结构与算法】 拓扑排序
数据结构·c++·算法
zth4130211 小时前
SegmentSplay‘s Super STL(v2.2)
开发语言·c++·算法
数据知道1 小时前
claw-code 源码详细分析:Bootstrap Graph——启动阶段图式化之后,排障与扩展为什么会变简单?
前端·算法·ai·bootstrap·claude code·claw code
Kel1 小时前
从Prompt到Response:大模型推理端到端核心链路深度拆解
人工智能·算法·架构
Felven1 小时前
D. Matryoshkas
算法