132 - Palindrome Partitioning II

博客围绕LeetCode上的一个算法问题展开,给定字符串s,需将其分割成每个子串都是回文串的形式,要求返回实现回文分割所需的最小切割数,并给出了问题链接。

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

Problem

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

Example:

Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

Code

public class Solution {

    public int minCut(String s) {
        int ls = s.length();
        int[] ans = new int[ls];
        List<Integer> arr = new LinkedList();
        for (int i = 0; i < ls; ++i) {
            arr.add(0, i);
            if (i == 0) {
                ans[i] = 0;
                continue;
            }
            ans[i] = ans[i - 1] + 1;
            List<Integer> tmp = new LinkedList<Integer>();
            tmp.add(i);
            for (int a : arr) {
                if (a != 0) {
                    if (s.charAt(a - 1) == s.charAt(i)) {
                        tmp.add(a - 1);
                        if (a - 1 == 0) {
                            ans[i] = 0;
                        } else {
                            if (ans[a - 2] + 1 < ans[i]) {
                                ans[i] = ans[a - 2] + 1;
                            }
                        }
                    }
                }
            }
            arr = tmp;
        }
        return ans[ls - 1];
    }
    
}

Link: https://leetcode.com/problems/palindrome-partitioning-ii/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值