Palindrome Partitioning II

Given a strings, partitionssuch that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning ofs.

For example, givens="aab", Return1since the palindrome partitioning["aa","b"]could be produced using 1 cut.

分析

区间dp

loop // interval :区间从小到大,先枚举区间长度。palindrome partition II
区间的话枚举,start and length
for(int length=2;length<s.length();length++)
    for(int start =0; start+length<s.length();start++)
        isP[start][start+length]=isP[start+1][start+length-1] &&s.charAt(start)==s.charAr(start+length)

2个dp,一个dp判断is palidrome,另一个根据结果得到cut。

2个循环i比j多1(不太懂)

cut[0]=-1 因为cut[1]=0 cut[1] = cut[0]+1 所以cut[0]=-1

2个dp合起来的版本

class Solution {
    public int minCut(String s) {
        int n = s.length();
        int cut[] = new int[n + 1];

        boolean[][] f = new boolean[n][n];
         cut[0] = -1;
        for(int i = 1; i <= n; i ++){ 
            cut[i] = i - 1;
            f[i - 1][i - 1] = true;
            for(int j = 0; j < i; j ++){
                f[j][i - 1] = s.charAt(i - 1) == s.charAt(j) && (i - 1 - j < 2 || f[j + 1][i - 2]) ;
                if(f[j][i - 1]){
                    cut[i] = Math.min(cut[i], cut[j] + 1);
                }
            }
        }

        return cut[n];
    }


}

分开dp

网上找的好理解版本。由图可知需要j-1

Last updated

Was this helpful?