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.


Test Cases

Example 1:

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

Example 2:

Input: s = "abaa"
Output: 1
Explanation: The palindrome partitioning ["aba","a"] could be produced using 1 cut.

Solution

class Solution {
public:
    int minCut(string s) {
        int n =s.length();
        bool dp[n][n];
        memset(dp, 0, sizeof(dp));
        int cut[n];
        for(int i=0; i<n; i++) {
            int mincut = i;
            for(int j=0; j<=i; j++) {
                if (s[i] == s[j] && (i-j < 2 || dp[j+1][i-1])) {
                    dp[j][i] = true;
                    mincut = min(mincut, j==0 ? 0 : cut[j-1]+1);
                }
            }
            cut[i] = mincut;
        }
        return cut[n-1];
    }
};
class Solution {
    public int minCut(String s) {
        int n =s.length();
        boolean[][] dp = new boolean[n][n];
        int[] cut= new int[n];
        for(int i=0; i<n; i++) {
            int mincut = i;
            for(int j=0; j<=i; j++) {
                if (s.charAt(i) == s.charAt(j) && (i-j < 2 || dp[j+1][i-1])) {
                    dp[j][i] = true;
                    mincut = Math.min(mincut, j==0 ? 0 : cut[j-1]+1);
                }
            }
            cut[i] = mincut;
        }
        return cut[n-1];
    }
}
Time Complexity: O(n2)
Space Complexity: O(n2)