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;
    }
相关推荐
ん贤16 分钟前
贪心算法.
算法·贪心算法
cndes24 分钟前
大数据算法的思维
大数据·算法·支持向量机
Mopes__2 小时前
Python | Leetcode Python题解之第461题汉明距离
python·leetcode·题解
睡不着还睡不醒2 小时前
【数据结构强化】应用题打卡
算法
sp_fyf_20242 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-05
人工智能·深度学习·神经网络·算法·机器学习·语言模型·自然语言处理
Mopes__3 小时前
Python | Leetcode Python题解之第452题用最少数量的箭引爆气球
python·leetcode·题解
C++忠实粉丝3 小时前
前缀和(6)_和可被k整除的子数组_蓝桥杯
算法
木向3 小时前
leetcode42:接雨水
开发语言·c++·算法·leetcode
TU^3 小时前
C语言习题~day16
c语言·前端·算法