LeeCode打卡 day26--切割回文串

本文介绍了在LeetCode上的第131题——分割回文串的解决方案。通过双指针判断回文串,然后使用回溯算法寻找所有可能的分割。代码中详细解释了backtrack函数的递归过程,以及如何构建和更新解空间。
摘要由CSDN通过智能技术生成

一个人的朝圣 — LeetCode打卡第26天


知识总结

今天做了两道组合问题在昨天已经写了, 重点讲一下切割问题


Leetcode 131. 分割回文串

题目链接

题目说明

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

回文串 是正着读和反着读都一样的字符串
在这里插入图片描述

代码说明

这道题其实很考验如何将问题转化
第一步: 运用双指针写出如何判断回文串的方法

第二部, 理解回溯的过程.

参照下面这幅图.
在这里插入图片描述

class Solution {
    List<List<String>> res = new ArrayList<>();
    LinkedList<String> path = new LinkedList<>();

    public List<List<String>> partition(String s) {
        backtrack(s, 0);
        return res;
    }

    public void backtrack(String s, int startIndex){
        if(startIndex == s.length()){
            res.add(new ArrayList<>(path));
        }

        for(int i = startIndex; i< s.length(); i++){
            if(isPalidrome(s, startIndex, i)){
                String str = s.substring(startIndex, i+1);
                path.add(str);
                backtrack(s, i+1);
                path.removeLast();
        		}
      		}
    	}

    public boolean isPalidrome(String s, int startIndex, int end){
        while(startIndex < end){
            if(s.charAt(startIndex++) != s.charAt(end--)){
                return false;
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值