LeetCode hot100-61-G

131. 分割回文串

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

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

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

C++ MAN
发布于 四川(编辑过)
2023.08.21

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;
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值