Skip to content

Commit dc55020

Browse files
committed
update palindrome partitioning logic
1 parent a1d66c4 commit dc55020

2 files changed

Lines changed: 26 additions & 30 deletions

File tree

‎src/com/interview/dynamic/PalindromePartition.java‎

Lines changed: 22 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -8,43 +8,36 @@
88
* Date 04/03/2016
99
* @author Tushar Roy
1010
*
11-
* http://www.geeksforgeeks.org/dynamic-programming-set-17-palindrome-partitioning/
11+
* Partitioning the string into palindromes.
12+
*
1213
* https://leetcode.com/problems/palindrome-partitioning/
14+
* https://leetcode.com/problems/palindrome-partitioning-ii/
1315
*/
1416
public class PalindromePartition {
1517

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;
2326
}
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]);
4436
}
4537
}
38+
cut[i] = min;
4639
}
47-
return T[0][T.length-1];
40+
return cut[str.length() - 1];
4841
}
4942

5043
/**

‎test/com/interview/dynamic/PalindromePartitionTest.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ public void testAllPartitions() {
3333
@Test
3434
public void palindromePartitionMinCuts() {
3535
PalindromePartition palindromePartition = new PalindromePartition();
36-
Assert.assertEquals(3, palindromePartition.minCuts("ABCCDCCLMLCCD".toCharArray()));
36+
Assert.assertEquals(3, palindromePartition.minCut("ABCCDCCLMLCCD"));
37+
Assert.assertEquals(0, palindromePartition.minCut("bb"));
38+
Assert.assertEquals(0, palindromePartition.minCut("b"));
39+
3740
}
3841
}

0 commit comments

Comments
 (0)