132. Palindrome Partitioning II (DP)

132. Palindrome Partitioning II

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.

My Solutions:

int[] cuts 储存对每个位置i的数来说,需要cut的最大值。最大cut数是i,代表每个位置都切一刀。最后返回cuts里最后的一个数。

boolean[][] dp 储存从j到i是否是palindrome。

状态转移方程:

if s.charAt(i) == s.charAt(j) 并且( j、i两数相邻或者两数之间的数也是palindrome),则记录dp[j][i]是palindrome true,同时更新cuts里此时i位置的数

  • 如果j是0,则取0,因为此时已经确认[0,i]都是palindrome,所以不需要切

  • 不然取cuts里此位置当前值或者是cuts[j - 1]的值+1,两者的最小值。cuts[j-1]+1是因为必须要在之前的基础上再切一刀才能满足现在形成的都是palindrome

e.g.1: aacd, cuts 初始化后是 [0,1,2,3]

只有a:cuts[0] = 0

aa:cuts[1] = 0

aac:i = 2, j =2 时才满足条件进入if loop,cuts[2] = cuts[1] + 1 = 1

aacd: i = 3, j = 3 时才满足条件进入if loop,cuts[3] = cuts[2] + 1 = 2

e.g.2: aacc, cuts = [0,1,2,3]

只有a:cuts[0] = 0

aa:cuts[1] = 0

aac:i = 2, j =2 时才满足条件进入if loop,cuts[2] = cuts[1] + 1 = 1

aacc: i = 3, j = 2 时才满足条件进入if loop,cuts[3] = cuts[1] + 1 = 1

e.g.3: aaab, cuts = [0,1,2,3]

只有a:cuts[0] = 0

aa:cuts[1] = 0

aaa:cuts[2]=0

aaab: i = 3, j = 3 时才满足条件进入if loop,cuts[3] = cuts[2] + 1 = 1

Time: O(n^2)

Space: O(n^2),二维dp

class Solution {
    public int minCut(String s) {
        if (s == null || s.length() == 0) return 0;
        
        int len = s.length();
        int[] cuts = new int[len];
        boolean[][] dp = new boolean[len][len];
        
        for (int i = 0; i < len; i++) {
            cuts[i] = i; //maximum cuts
            for (int j = 0; j <= i; j++) {
                if (s.charAt(j) == s.charAt(i) && 
                    (i - j <= 1 || dp[j + 1][i - 1])) {
                    dp[j][i] = true;
                    cuts[i] = j == 0 ? 0 : Math.min(cuts[i], cuts[j - 1] + 1);
                }
            }
        }
        return cuts[len - 1];
    }

}

Last updated