LeetCode - Palindrome Partitioning II

1 minute read

Problem description

description

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:

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

Analysis

First we can use a dp to find all palindromic substring. And we can use another dp to store the cur. dp[i] is the min cut for substring(0,i)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int minCut(String s) {
    char[] c = s.toCharArray();
    int n = c.length;
    int[] cut = new int[n];
    boolean[][] pal = new boolean[n][n];
    
    for(int i = 0; i < n; i++) {
        int min = i;
        for(int j = 0; j <= i; j++) {
            if(c[j] == c[i] && (j + 1 > i - 1 || pal[j + 1][i - 1])) {
                pal[j][i] = true;
                min = j == 0 ? 0 : Math.min(min, cut[j - 1] + 1);
            }
        }
        cut[i] = min;
    }
    return cut[n - 1];
}

What to improve

  • when we do cut for palindromic substring, we can use a cut array as a dp and don’t use the general dfs method.