Palindrome Partitioning II
Given a string s, partition it such that every substring of the partition is a palindrome. Return the minimum number of cuts needed.
Example 1
Input: s = "aab" → Output: 1 (["aa","b"])
Example 2
Input: s = "a" → Output: 0
Solution Approach
Use dynamic programming. First precompute a 2D isPalin[i][j] table. Then use dp[i] = minimum cuts for s[0..i]. For each i, if s[0..i] is a palindrome dp[i]=0; otherwise dp[i] = min over all j where s[j+1..i] is a palindrome of dp[j]+1.
- Precompute isPalin[i][j] using DP: isPalin[i][j] = s[i]==s[j] && isPalin[i+1][j-1].
- Initialize dp[i] = i (max cuts = i for length i+1 prefix).
- For each i, if isPalin[0][i], set dp[i]=0.
- Otherwise, for each j from 1 to i, if isPalin[j][i], set dp[i] = min(dp[i], dp[j-1]+1).
Java
class Solution {
public int minCut(String s) {
int n = s.length();
boolean[][] isPalin = new boolean[n][n];
for (int len = 1; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
isPalin[i][j] = s.charAt(i) == s.charAt(j)
&& (len <= 2 || isPalin[i + 1][j - 1]);
}
}
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
if (isPalin[0][i]) { dp[i] = 0; continue; }
dp[i] = i;
for (int j = 1; j <= i; j++) {
if (isPalin[j][i]) dp[i] = Math.min(dp[i], dp[j - 1] + 1);
}
}
return dp[n - 1];
}
}
- Time Complexity: O(N^2)
- Space Complexity: O(N^2). isPalin table