- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSolution131.java
More file actions
Latest commit
executable file
·59 lines (48 loc) · 1.72 KB
/
Copy pathSolution131.java
File metadata and controls
executable file
·59 lines (48 loc) · 1.72 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
importjava.util.ArrayList;
importjava.util.List;
/**
* Created by slade on 2019/6/26.
*/
publicclassSolution131 {
List<List<String>> ans = newArrayList<>();
publicList<List<String>> partition(Strings) {
List<String> ansValue = newArrayList<>();
if (s == "" || s.length() == 0) {
returnans;
}
subPartition(s, 0, ansValue);
returnans;
}
publicvoidsubPartition(Strings, intindex, List<String> ansValue) {
if (s.length() == index) {
ans.add(ansValue);
return;
}
for (inti = index + 1; i <= s.length(); ++i) {
if (isPalindrome(s.substring(index, i))) {
ansValue.add(s.substring(index, i));
//已经用ansValue用的是内存地址,时刻在变,所以要new ArrayList<String>(ansValue)固定值使其不变
subPartition(s, i, newArrayList<>(ansValue));
//因为每次执行subPartition会额外add一个其他元素,当所有结果尝试完成或者不满足要求的时候,需要进行回溯把迭代多少次额外加的元素全部剔除
ansValue.remove(ansValue.size() - 1);
}
}
}
publicbooleanisPalindrome(Strings) {
if (s == "" || s.length() == 0) {
returnfalse;
}
//前缀是否回文
for (intj = 0; j < s.length() / 2; j++) {
if (s.charAt(j) != s.charAt(s.length() - j - 1)) {
returnfalse;
}
}
returntrue;
}
publicstaticvoidmain(String[] args) {
Strings = "abc";
Solution131obj = newSolution131();
System.out.println(obj.partition(s));
}
}