|
8 | 8 | * Date 04/03/2016 |
9 | 9 | * @author Tushar Roy |
10 | 10 | * |
11 | | - * http://www.geeksforgeeks.org/dynamic-programming-set-17-palindrome-partitioning/ |
| 11 | + * Partitioning the string into palindromes. |
| 12 | + * |
12 | 13 | * https://leetcode.com/problems/palindrome-partitioning/ |
| 14 | + * https://leetcode.com/problems/palindrome-partitioning-ii/ |
13 | 15 | */ |
14 | 16 | public class PalindromePartition { |
15 | 17 |
|
16 | | - public int minCuts(char[] str){ |
17 | | - |
18 | | - int T[][] = new int[str.length][str.length]; |
19 | | - boolean P[][] = new boolean[str.length][str.length]; |
20 | | - |
21 | | - for(int i=0; i < P.length; i++){ |
22 | | - P[i][i] = true; |
| 18 | + /* |
| 19 | + * Given a string s, partition s such that every substring of the partition is a palindrome. |
| 20 | + * Return the minimum cuts needed for a palindrome partitioning of s. |
| 21 | + * https://leetcode.com/problems/palindrome-partitioning-ii/ |
| 22 | + */ |
| 23 | + public int minCut(String str){ |
| 24 | + if (str.length() == 0) { |
| 25 | + return 0; |
23 | 26 | } |
24 | | - |
25 | | - for(int l= 2; l <= str.length; l++){ |
26 | | - for(int i = 0; i <= str.length - l; i++){ |
27 | | - int j = i + l-1; |
28 | | - if(l == 2){ |
29 | | - P[i][j] = str[i] == str[j]; |
30 | | - }else{ |
31 | | - P[i][j] = (str[i] == str[j]) && P[i+1][j-1]; |
32 | | - } |
33 | | - if(P[i][j]){ |
34 | | - T[i][j] = 0; |
35 | | - }else{ |
36 | | - T[i][j] = 10000; |
37 | | - int r = 0; |
38 | | - for(int k = i; k < j; k++){ |
39 | | - r = T[i][k] + T[k+1][j] +1 ; |
40 | | - if(r < T[i][j]){ |
41 | | - T[i][j] = r; |
42 | | - } |
43 | | - } |
| 27 | + |
| 28 | + int[] cut = new int[str.length()]; |
| 29 | + boolean isPal[][] = new boolean[str.length()][str.length()]; |
| 30 | + for (int i = 1; i < str.length(); i++) { |
| 31 | + int min = i; |
| 32 | + for (int j = 0; j <= i; j++) { |
| 33 | + if (str.charAt(i) == str.charAt(j) && (i <= j + 1 || isPal[i - 1][j + 1])) { |
| 34 | + isPal[i][j] = true; |
| 35 | + min = Math.min(min, j == 0 ? 0 : 1 + cut[j - 1]); |
44 | 36 | } |
45 | 37 | } |
| 38 | + cut[i] = min; |
46 | 39 | } |
47 | | - return T[0][T.length-1]; |
| 40 | + return cut[str.length() - 1]; |
48 | 41 | } |
49 | 42 |
|
50 | 43 | /** |
|
0 commit comments