|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/**Given a string s, partition s such that every substring of the partition is a palindrome. |
| 3 | +/** |
| 4 | + * 132. Palindrome Partitioning II |
| 5 | +
|
| 6 | + Given a string s, partition s such that every substring of the partition is a palindrome. |
4 | 7 |
|
5 | 8 | Return the minimum cuts needed for a palindrome partitioning of s.
|
6 | 9 |
|
|
9 | 12 |
|
10 | 13 | */
|
11 | 14 | public class _132 {
|
12 |
| - /**This solution is cooler than Jiuzhang: https://discuss.leetcode.com/topic/32575/easiest-java-dp-solution-97-36*/ |
13 |
| - |
14 |
| - //cut[i] stands for the minimum number of cut needed to cut [0, i] into palindromes |
15 |
| - //we initiazlie cut[i] with its max possible value which is i, this is because a single char is naturally a palindrome, so, we'll cut this string into all single-char substrings, which is the max cuts needed |
16 |
| - |
17 |
| - //dp[j][i] == true stands for s.substring(j,i) is a palindrome |
18 |
| - public int minCut(String s) { |
| 15 | + |
| 16 | + /**This solution is cooler than Jiuzhang: https://discuss.leetcode.com/topic/32575/easiest-java-dp-solution-97-36*/ |
| 17 | + |
| 18 | + public static class Solution1 { |
| 19 | + //cut[i] stands for the minimum number of cut needed to cut [0, i] into palindromes |
| 20 | + //we initiazlie cut[i] with its max possible value which is i, this is because a single char is naturally a palindrome, so, we'll cut this string into all single-char substrings, which is the max cuts needed |
| 21 | + |
| 22 | + //dp[j][i] == true stands for s.substring(j,i) is a palindrome |
| 23 | + public int minCut(String s) { |
19 | 24 | int n = s.length();
|
20 | 25 | char[] c = s.toCharArray();
|
21 | 26 | boolean[][] dp = new boolean[n][n];
|
22 | 27 | int[] cut = new int[n];
|
23 | 28 |
|
24 | 29 | for (int i = 0; i < n; i++) {
|
25 |
| - cut[i] = i; |
26 |
| - for (int j = 0; j <= i; j++) { |
27 |
| - if (c[i] == c[j] && (j + 1 > i - 1 || dp[j + 1][i - 1])) { |
28 |
| - dp[j][i] = true; |
29 |
| - if (j == 0) { |
30 |
| - cut[i] = 0; |
31 |
| - } else { |
32 |
| - cut[i] = (cut[i] < cut[j - 1] + 1) ? cut[i] : cut[j - 1] + 1; |
33 |
| - } |
34 |
| - } |
| 30 | + cut[i] = i; |
| 31 | + for (int j = 0; j <= i; j++) { |
| 32 | + if (c[i] == c[j] && (j + 1 > i - 1 || dp[j + 1][i - 1])) { |
| 33 | + dp[j][i] = true; |
| 34 | + if (j == 0) { |
| 35 | + cut[i] = 0; |
| 36 | + } else { |
| 37 | + cut[i] = (cut[i] < cut[j - 1] + 1) ? cut[i] : cut[j - 1] + 1; |
| 38 | + } |
35 | 39 | }
|
| 40 | + } |
36 | 41 | }
|
37 | 42 |
|
38 | 43 | return cut[n - 1];
|
| 44 | + } |
39 | 45 | }
|
40 | 46 | }
|
0 commit comments