Skip to content

Commit 04e2c00

Browse files
committed
palindrome partitioning
1 parent 433a8ff commit 04e2c00

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/palindrome-partitioning/
8+
public class PalindromePartitioning {
9+
10+
public static void main(String[] args) {
11+
String s = "aab";
12+
PalindromePartitioning obj = new PalindromePartitioning();
13+
List<List<String>> resultList = obj.partition(s);
14+
System.out.println(Arrays.toString(resultList.toArray()));
15+
}
16+
17+
public List<List<String>> partition(String s) {
18+
List<List<String>> resultList = new ArrayList<List<String>>();
19+
// dfs
20+
dfs(s, 0, resultList, new ArrayList<String>());
21+
22+
return resultList;
23+
}
24+
25+
private void dfs(String s, int start, List<List<String>> resultList, List<String> list) {
26+
// exit
27+
if (start >= s.length()) {
28+
resultList.add(new ArrayList<String>(list));
29+
return;
30+
}
31+
32+
// for
33+
for (int i = start; i < s.length(); i++) {
34+
35+
// isPalindrome
36+
if (isPal(s, start, i)) {
37+
// add
38+
list.add(s.substring(start, i + 1));
39+
dfs(s, i + 1, resultList, list);
40+
41+
// not add
42+
list.remove(list.size() - 1);
43+
}
44+
}
45+
}
46+
47+
private boolean isPal(String s, int l, int r) {
48+
while (l < r) {
49+
if (s.charAt(l++) != s.charAt(r--)) {
50+
return false;
51+
}
52+
}
53+
54+
return true;
55+
}
56+
}

0 commit comments

Comments
 (0)