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;
    }
相关推荐
夜思红尘5 小时前
算法--双指针
python·算法·剪枝
散峰而望5 小时前
【算法竞赛】C++函数详解:从定义、调用到高级用法
c语言·开发语言·数据结构·c++·算法·github
CoderCodingNo5 小时前
【GESP】C++五级真题(贪心思想考点) luogu-B4071 [GESP202412 五级] 武器强化
开发语言·c++·算法
我有一些感想……5 小时前
An abstract way to solve Luogu P1001
c++·算法·ai·洛谷·mlp
前端小L5 小时前
双指针专题(三):去重的艺术——「三数之和」
javascript·算法·双指针与滑动窗口
在风中的意志5 小时前
[数据库SQL] [leetcode] 2388. 将表中的空值更改为前一个值
数据库·sql·leetcode
智者知已应修善业6 小时前
【求等差数列个数/无序获取最大最小次大次小】2024-3-8
c语言·c++·经验分享·笔记·算法
还不秃顶的计科生7 小时前
LeetCode 热题 100第二题:字母易位词分组python版本
linux·python·leetcode
LYFlied7 小时前
【每日算法】LeetCode 416. 分割等和子集(动态规划)
数据结构·算法·leetcode·职场和发展·动态规划
多米Domi0117 小时前
0x3f 第19天 javase黑马81-87 ,三更1-23 hot100子串
python·算法·leetcode·散列表