-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathPalindromePartitioning.java
More file actions
44 lines (38 loc) · 1.09 KB
/
PalindromePartitioning.java
File metadata and controls
44 lines (38 loc) · 1.09 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
/**
* LeetCode 131 https://leetcode.com/problems/palindrome-partitioning/
*/
class Solution {
List<List<String>> res = new LinkedList<>();
LinkedList<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
backtrack(s, 0);
return res;
}
void backtrack (String s, int startIndex) {
// base case
if (startIndex == s.length()) {
res.add(new LinkedList(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if(isPalindrome(s, startIndex, i)) {
String str = s.substring(startIndex, i + 1);
path.add(str);
} else {
continue;
}
backtrack(s, i+1);
path.removeLast();
}
}
boolean isPalindrome(String s, int start, int end) {
while (start <= end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}