lc131 分割回文串

16 篇文章 0 订阅
15 篇文章 0 订阅

这个题目的难点是分割,然后思路的话,还是比较常规,回溯就行

注意需要使用一个start去记录左边界,那么右边界就是i,因为左边的start是上一个的结束位置

代码如下:

package com.codeking.lc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiongjl
 * @since 2023/9/22  16:04
 */
public class lc131 {
    public static void main(String[] args) {
        lc131 lc131 = new lc131();
        List<List<String>> efe = lc131.partition("efe");
        System.out.println(efe);
    }
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        backTracing(res, new ArrayList<>(), s, 0);
        return res;
    }

    void backTracing(List<List<String>> res, List<String> cur,String s,int start) {
        if (start==s.length()) {
            res.add(new ArrayList<>(cur));
        }
        for (int i = start; i < s.length(); i++) {
            // 分割字符串
            String temp = s.substring(start, i+1);
            // 直接判断是不是回文
            if (isPalindrome(temp)) {
                cur.add(temp);
                backTracing(res, cur, s, i+1);
                cur.remove(cur.size() - 1);
            }
        }
    }

    //  写一个判断回文子串
    boolean isPalindrome(String s) {
        char[] str = s.toCharArray();
        // 前后遍历就行
        for (int i = 0; i <= str.length / 2; i++) {
            int start = str[i];
            int end = str[str.length - 1 - i];
            if (start != end) {
                return false;
            }
        }
        return true;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值