-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromPartitioning.java
More file actions
43 lines (37 loc) · 1.26 KB
/
PalindromPartitioning.java
File metadata and controls
43 lines (37 loc) · 1.26 KB
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
import java.util.ArrayList;
import java.util.List;
public class PalindromPartitioning {
public static void main(String[] args) {
String s = "aab";
List<List<String>> result = partition(s);
System.out.println(result);
}
public static List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
backtrack(s, 0, new ArrayList<>(), result);
return result;
}
private static void backtrack(String s, int start, List<String> currentList, List<List<String>> result) {
if (start >= s.length()) {
result.add(new ArrayList<>(currentList));
return;
}
for (int end = start; end < s.length(); end++) {
if (isPalindrome(s, start, end)) {
currentList.add(s.substring(start, end + 1));
backtrack(s, end + 1, currentList, result);
currentList.remove(currentList.size() - 1);
}
}
}
private static boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}