-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution131.java
63 lines (55 loc) · 1.59 KB
/
Solution131.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
59
60
61
62
63
package algorithm.leetcode;
import java.util.LinkedList;
import java.util.List;
/**
* @author: mayuan
* @desc: 分割回文串
* @date: 2018/08/13
*/
public class Solution131 {
public static void main(String[] args) {
String str = "aab";
Solution131 test = new Solution131();
List<List<String>> result = test.partition(str);
result.forEach(list -> {
for (String item : list) {
System.out.print(item);
System.out.print(" ");
}
System.out.println();
});
}
public List<List<String>> partition(String s) {
List<List<String>> answer = new LinkedList<>();
dfs(answer, new LinkedList<>(), s);
return answer;
}
private void dfs(List<List<String>> answer, List<String> oneAnswer, String s) {
if (0 == s.length()) {
answer.add(new LinkedList<>(oneAnswer));
return;
}
for (int i = 0; i < s.length(); i++) {
if (isPalindrome(s, 0, i)) {
oneAnswer.add(s.substring(0, i + 1));
dfs(answer, oneAnswer, s.substring(i + 1));
oneAnswer.remove(oneAnswer.size() - 1);
}
}
}
/**
* 判断该字符串是否是回文字符串
* @param str
* @param left
* @param right
* @return
*/
private boolean isPalindrome(String str, int left, int right) {
while (left < right) {
if (str.charAt(left++) != str.charAt(right--)) {
return false;
}
}
return true;
}
}