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.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

Solution:

  1. public class Solution {
  2. public int minCut(String s) {
  3. if (s == null || s.length() == 0) {
  4. return 0;
  5. }
  6. int n = s.length();
  7. // build the dp matrix to hold the palindrome information
  8. // dp[i][j] represents whether s[i] to s[j] can form a palindrome
  9. boolean[][] dp = buildMatrix(s, n);
  10. // res[i] represents the minimum cut needed
  11. // from s[0] to s[i]
  12. int[] res = new int[n];
  13. for (int j = 0; j < n; j++) {
  14. // by default we need j cut from s[0] to s[j]
  15. int cut = j;
  16. for (int i = 0; i <= j; i++) {
  17. if (dp[i][j]) {
  18. // s[i] to s[j] is a palindrome
  19. // try to update the cut with res[i - 1]
  20. cut = Math.min(cut, i == 0 ? 0 : res[i - 1] + 1);
  21. }
  22. }
  23. res[j] = cut;
  24. }
  25. return res[n - 1];
  26. }
  27. boolean[][] buildMatrix(String s, int n) {
  28. boolean[][] dp = new boolean[n][n];
  29. for (int i = n - 1; i >= 0; i--) {
  30. for (int j = i; j < n; j++) {
  31. if (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])) {
  32. dp[i][j] = true;
  33. }
  34. }
  35. }
  36. return dp;
  37. }
  38. }