-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathPalindromicPartitioning.java
45 lines (39 loc) · 1.38 KB
/
PalindromicPartitioning.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.leetcode.year_2020.backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* https://leetcode.com/problems/palindrome-partitioning/description/
*
* @author neeraj on 10/04/20
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
public class PalindromicPartitioning {
public static void main(String[] args) {
// System.out.println(partition("aab"));
System.out.println(partition("aabb"));
}
public static List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
palindromicSubset(s, 0, new ArrayList<>(), result);
return result;
}
private static void palindromicSubset(String s, int pointer, ArrayList<String> subset, List<List<String>> result) {
if (pointer == s.length()) {
System.out.println(subset);
result.add(new ArrayList<>(subset));
return;
}
for (int i = pointer; i < s.length(); i++) {
if (isPalindrome(s.substring(pointer, i + 1))) {
subset.add(s.substring(pointer, i + 1));
palindromicSubset(s, i + 1, subset, result);
subset.remove(subset.size() - 1);
}
}
}
private static boolean isPalindrome(String str) {
String temp = str;
return new StringBuffer(str).reverse().toString().equals(temp);
}
}