GuilinDev

Lc0132

05 August 2008

Palindrome Partitioning II

给一个string,分成若干sub strings,使每个substring都是回文,跟131相比,返回最小的cut的解法

cut[i] is the minimum of cut[j - 1] + 1 (j <= i), if [j, i] is palindrome.

If [j, i] is palindrome, [j + 1, i - 1] is palindrome, and c[j] == c[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];
}