-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path131. Palindome partitioning
42 lines (33 loc) · 1.09 KB
/
131. Palindome partitioning
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
//131. Palindome partitioning
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
backtrack(s, 0, new ArrayList<>(), result);
return result;
}
private void backtrack(String s, int start, List<String> path, List<List<String>> result) {
if(start == s.length()) {
result.add(new ArrayList<>(path));
return;
}
for(int end = start + 1; end <= s.length(); end++) {
String currentSub = s.substring(start, end);
if(isPalindrome(currentSub)) {
path.add(currentSub);
backtrack(s, end, path, result);
path.remove(path.size() - 1);
}
}
}
private boolean isPalindrome(String sub) {
int left = 0, right = sub.length() - 1;
while(left < right) {
if(sub.charAt(left) != sub.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}