Skip to content

Double Sequence XI

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.

https://leetcode.com/problems/palindrome-partitioning-ii/description/

Example I:

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

Questions

  • LeetCode - 132. Palindrome Partitioning II

Transform Function

for(int i = 0; i < n; i++) {
    dp[i] = i;
    for(int j = 0; j <= i; j++) {
        if(s.charAt(i) == s.charAt(j) && (i - j < 2 || p[j + 1][i - 1])) {
            p[j][i] = true;
            dp[i] = (j == 0) ? 0 : Math.min(dp[i], dp[j - 1] + 1);
        }
    }
}

Solution I

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