力扣:分割回文串

题目描述


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

输入:s = “aab”
输出:[ [ “a” , “a” , “b” ] , [ “aa” , “b” ] ]

如果有了 组合总和 系列刷题经历,此题就大同小异 ,(图片来源:)
在这里插入图片描述

class Solution {

    List<List<String>> result = new ArrayList<>();
    public List<List<String>> partition(String s) {
        List<String> path = new ArrayList<>();
        backtracking(path , s , 0);
        return result;
    }

    public void backtracking(List<String> path , String s , int start){
        // 如果 起始位置 已经大于 s 的 大小 , 则说明已经找到了一组分割方案
        if(start >= s.length()){
            result.add(new ArrayList<>(path));
            return ;
        }

        for(int i = start ; i < s.length() ; i ++){
            if(isPalindrome(s , start , i)) { // 是回文子串
                // 获取 [start , i] 在 sb 中的子串
                String str = s.substring(start , i + 1); // substring 方法是 左闭右开
                path.add(str);
            } else {
                continue;
            }
            backtracking(path , s , i + 1); 
            path.remove(path.size() - 1);
        }
    }
    public boolean isPalindrome(String s, int start, int end) {
        for (int i = start , j = end ; i < j ; i ++ , j --) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值