-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy path131_Palindrome_Partitioning.java
40 lines (33 loc) · 1.02 KB
/
131_Palindrome_Partitioning.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
class Solution {
public List<List<String>> partition(String s) {
if (s == null || s.length() == 0) {
return Collections.emptyList();
}
List<List<String>> result = new ArrayList<>();
helper(s, 0, result, new ArrayList<>());
return result;
}
private void helper(String s, int idx, List<List<String>> result, List<String> temp) {
if (idx == s.length()) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = idx; i < s.length(); i++) {
if (isPalindrome(s, idx, i)) {
temp.add(s.substring(idx, i + 1));
helper(s, i + 1, result, temp);
temp.remove(temp.size() - 1);
}
}
}
private boolean isPalindrome(String s, int left, int right) {
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
++left;
--right;
}
return true;
}
}