Given a string s, partition it such that every substring of the partition is a palindrome. Return the minimum number of cuts needed.

Input: s = "aab" → Output: 1 (["aa","b"])Input: s = "a" → Output: 0

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.

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]; } }