-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome_Partionting.java
More file actions
48 lines (43 loc) · 1.42 KB
/
Palindrome_Partionting.java
File metadata and controls
48 lines (43 loc) · 1.42 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
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> parts = new ArrayList<ArrayList<String>>();
if ((s == null) || (s.length() == 0)) {
return parts;
}
getParts(parts, s, 0, null);
return parts;
}
private void getParts(ArrayList<ArrayList<String>> parts, String s, int start, ArrayList<String> prefix) {
if (start >= s.length()) {
if (prefix != null) {
parts.add(prefix);
}
}
for (int i = start; i < s.length(); i++) {
String str = s.substring(start,i+1);
if (isPalindrome(str)) {
ArrayList<String> newPrefix;
if (prefix == null) {
newPrefix = new ArrayList<String>();
newPrefix.add(str);
} else {
newPrefix = new ArrayList<String>(prefix);
newPrefix.add(str);
}
getParts(parts, s, i+1, newPrefix);
}
}
}
private boolean isPalindrome(String str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
if (str.charAt(start) != str.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}