LeetCode.131 分割回文串

本文介绍了如何使用回溯算法解决LeetCode上的131题——回文划分。通过Java代码实现,详细展示了如何判断字符串子串是否为回文,并进行深度优先搜索来找到所有可能的回文子串组合。代码中包括关键函数如isHuiWen()用于检查回文,以及dfs()进行深度遍历。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题

https://leetcode-cn.com/problems/palindrome-partitioning/
在这里插入图片描述

思路

回溯算法

题解

package com.leetcode.code;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * @Description:
 * @ClassName: Code131
 * @Author: ZK
 * @Date: 2021/3/7 22:25
 * @Version: 1.0
 */
public class Code131 {

    public static void main(String[] args) {
        String s = "aab";
        List<List<String>> res = partition(s);
        for (List<String> list : res) {
            System.out.println(list);
        }
    }

    public static List<List<String>> partition(String s) {
        int len = s.length();
        List<List<String>> res = new ArrayList<>();
        if (len == 0) {
            return res;
        }

        Stack<String> stack = new Stack<>();
        char[] chars = s.toCharArray();
        dfs(chars, 0, len, stack, res);
        return res;
    }

    /**
     * dfs
     * @param chars     字符数组
     * @param index     起始下标
     * @param len       字符串长度
     * @param stack     栈,用来存储子串
     * @param res       存储所有的结果
     */
    public static void dfs(char[] chars, int index, int len, Stack<String> stack, List<List<String>> res){
        if (index == len) {
            res.add(new ArrayList<>(stack));
            return;
        }
        for (int i = index; i < len; i++) {
//            判断当前子串是否回文
            if (!isHuiWen(chars, index, i)) {
                continue;
            }
//            如果回文,则添加到栈中
            stack.push(new String(chars, index, i-index+1));
            dfs(chars, i+1, len, stack, res);
//            回溯
            stack.pop();
        }
    }

    /**
     * 判断一个字符串是否回文
     * @param chars     字符数组
     * @param left      起始下标,包含
     * @param right     结束下标,包含
     * @return
     */
    public static boolean isHuiWen(char[] chars, int left, int right){
        while(left < right){
            if (chars[left] != chars[right]) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值