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.

Analysis

左大段, 右小段; Midterm 2. Solution 1: O(n^3). Solution 2: O(n ^ 2);

Solution 1

public int minCut(String s) {
    if (s == null || s.length() < 2) {
        return 0;
    }
    int[] m = new int[s.length() + 1];
    for (int i = 1; i <= s.length(); ++i) {
        if (isPal(s, 0, i - 1)) {
            m[i] = 0;
            continue;
        }
        m[i] = i - 1;
        for (int j = 1; j < i; ++j) {
            if (isPal(s, j, i - 1)) {
                m[i] = Math.min(m[i], m[j] + 1);
            }
        }
    }
    return m[m.length - 1];
}
private boolean isPal(String s, int left, int right) {
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) {
            return false;
        }
        left++; right--;
    }
    return true;
}

Solution 2

public int minCut(String s) {
    char[] ch = s.toCharArray();
    int n = ch.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 (ch[j] == ch[i] && (i - j < 2 || 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];
}

results matching ""

    No results matching ""