LeetCode hot100-61-G

java 复制代码
131. 分割回文串

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

做不来,官方答案一大坨都不想看,评论区找了个答案跑了一下,感觉还不错,但是自己还是写不出来这种题,后面得做专项总结,回溯包括大部分递归都是直接看答案看过去了,真菜。

https://leetcode.cn/problems/palindrome-partitioning/description/?envType=study-plan-v2\&envId=top-100-liked

C++ MAN

发布于 四川(编辑过)

2023.08.21

java 复制代码
public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        partition(s, 0, 0, new ArrayList<>(), res);
        return res;
  }
public void partition(String s, int start, int end, List<String> tempRes, List<List<String>> res) {
        //如果分隔起点超出了字符串长度,说明已经分隔完,直接将结果返回
        if (start == s.length()) {
            res.add(new ArrayList<>(tempRes));
            return;
        }
        //如果分隔终点超出了字符串,直接返回
        if (end == s.length()) {
            return;
        }
        //当前不进行拆分,直接将end+1
        partition(s, start, end + 1, tempRes, res);
        //当前进行拆分
        String part = s.substring(start, end + 1);
        //是回文字符串,加入到结果中
        if (isPalindrome(part)) {
            tempRes.add(part);
            //start和end更新为分隔部分的下一个字符
            partition(s, end + 1, end + 1, tempRes, res);
            //回溯
            tempRes.remove(tempRes.size() - 1);
        }
    }
    private boolean isPalindrome(String s) {
        int start =0;
        int end = s.length() - 1;
        while (start <= end) {
            if (s.charAt(start) != s.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
相关推荐
songx_9910 小时前
leetcode10(跳跃游戏 II)
数据结构·算法·leetcode
先做个垃圾出来………11 小时前
差分数组(Difference Array)
java·数据结构·算法
hansang_IR11 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息11 小时前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
多恩Stone11 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
惯导马工13 小时前
【论文导读】IDOL: Inertial Deep Orientation-Estimation and Localization
深度学习·算法
老姜洛克13 小时前
自然语言处理(NLP)之n-gram从原理到实战
算法·nlp
1白天的黑夜113 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表
CoovallyAIHub13 小时前
基于YOLO集成模型的无人机多光谱风电部件缺陷检测
深度学习·算法·计算机视觉
CoovallyAIHub13 小时前
几十个像素的小目标,为何难倒无人机?LCW-YOLO让无人机小目标检测不再卡顿
深度学习·算法·计算机视觉