-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay40.java
More file actions
52 lines (44 loc) · 1.56 KB
/
Day40.java
File metadata and controls
52 lines (44 loc) · 1.56 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
44
45
46
47
48
49
50
51
52
import java.util.ArrayList;
import java.util.List;
public class Day40 {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
List<String> currentPartition = new ArrayList<>();
backtrack(s, 0, currentPartition, result);
return result;
}
private void backtrack(String s, int start, List<String> currentPartition, List<List<String>> result) {
if (start == s.length()) {
result.add(new ArrayList<>(currentPartition));
return;
}
for (int end = start; end < s.length(); end++) {
if (isPalindrome(s, start, end)) {
currentPartition.add(s.substring(start, end + 1));
backtrack(s, end + 1, currentPartition, result);
currentPartition.remove(currentPartition.size() - 1);
}
}
}
private boolean isPalindrome(String s, int start, int end) {
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
public static void main(String[] args) {
Day40 solution = new Day40();
String s1 = "aab";
List<List<String>> result1 = solution.partition(s1);
System.out.println("Example 1:");
System.out.println(result1);
String s2 = "a";
List<List<String>> result2 = solution.partition(s2);
System.out.println("Example 2:");
System.out.println(result2);
}
}