LeetCode Palindrome Partitioning II

23 篇文章 0 订阅

原题链接在这里:https://leetcode.com/problems/palindrome-partitioning-ii/


这道题与Word Break相似。用DP来做,需要保留的历史信息就是到当前点能分成几块Palindrome, 用一个int数组res保留。每次更新res[i+1], 比较i+1和res[j]+1大小,取小的。因为单个letter肯定是palindrome, 所以肯定会被字典拆开,但[j...i]这一段可能是一个palindrome, 所以数量应更新成res[j]+1与i+1中较小的一个。

用二维boolean数组存储字典,boolean[i][j]表示从i到j这一段是否是回文。

Note: 1. helper当中判断使用dict[i+1][j-1]之前需先判定i,j 是否out of index了,这类问题都是如此,需先判断index有没有out of bound.

2. minCut中,双层loop的内层loop, j 是由 0 到 i, 判断isDic[j][i]是否为true.

AC Java:

public class Solution {
    public int minCut(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }
        int len = s.length();
        boolean[][] isDic = helper(s);
        int [] res = new int[len+1];
        res[0] = 0;
        for(int i = 0; i < len; i++){
            res[i+1] = i+1;
            for(int j = 0; j <= i; j++){        //error
                if(isDic[j][i]){
                    res[i+1] = Math.min(res[i+1],res[j]+1);
                }
            }
        }
        return res[len] - 1;
    }
    
    //helper function builds dictionary
    private boolean[][] helper(String s){
        int len = s.length();
        boolean[][] dict = new boolean[len][len];
        for(int i = len-1; i>=0; i--){
            for(int j = i; j < len; j++){
                if(s.charAt(i) == s.charAt(j) && ((j-i)<2 || dict[i+1][j-1] )){     //error
                    dict[i][j] = true;
                }
            }
        }
        return dict;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值