-
Notifications
You must be signed in to change notification settings - Fork 819
/
PalindromePartitioning.java
58 lines (53 loc) · 1.43 KB
/
PalindromePartitioning.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* Created by pradhang on 3/15/2017. Given a string s, partition s such that every substring of the
* partition is a palindrome.
*
* <p>Return all possible palindrome partitioning of s.
*
* <p>For example, given s = "aab", Return
*
* <p>[ ["aa","b"], ["a","a","b"] ]
*/
public class PalindromePartitioning {
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
List<List<String>> result = new PalindromePartitioning().partition("aaaaaaaaaaaaaaaaaa");
}
public List<List<String>> partition(String s) {
List<List<String>> result = new ArrayList<>();
doNext(0, new ArrayList<>(), s, result);
return result;
}
private void doNext(int i, List<String> row, String s, List<List<String>> result) {
if (i == s.length()) {
List<String> list = new ArrayList<>(row);
result.add(list);
} else {
for (int j = i, l = s.length(); j < l; j++) {
String sbStr = s.substring(i, j + 1);
if (isPalindrome(sbStr)) {
row.add(sbStr);
doNext(j + 1, row, s, result);
row.remove(row.size() - 1);
}
}
}
}
private boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i <= j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++;
j--;
}
return true;
}
}