forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome Partitioning.java
More file actions
49 lines (42 loc) · 1.38 KB
/
Palindrome Partitioning.java
File metadata and controls
49 lines (42 loc) · 1.38 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
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
ArrayList<String> pt = new ArrayList<String>();
findPartition(s, 0, pt, results);
return results;
}
public void findPartition(String s, int begin, ArrayList<String> pt, ArrayList<ArrayList<String>> results) {
if (begin >= s.length()) {
ArrayList<String> copy = new ArrayList<String>();
for (int j = 0; j < pt.size(); j++) {
copy.add(pt.get(j));
}
results.add(copy);
}
for (int i = begin; i < s.length(); i++) {
if (isPalindrome(s, begin, i)) {
pt.add(s.substring(begin, i + 1));
findPartition(s, i + 1, pt, results);
pt.remove(pt.size() - 1);
}
}
}
boolean isPalindrome(String s, int start, int end) {
while(start < end) {
if(s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}