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) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, ArrayList<ArrayList<String>>> groups = new HashMap<Integer, ArrayList<ArrayList<String>>>();
ArrayList<ArrayList<String>> group0 = new ArrayList<ArrayList<String>>();
ArrayList<String> t = new ArrayList<String>();
t.add(s.substring(0, 1));
group0.add(t);
groups.put(0, group0);
boolean cache[][] = new boolean[s.length()][s.length()];
for(int i=1;i<s.length();i++) {
ArrayList<ArrayList<String>> newGroup = new ArrayList<ArrayList<String>>();
String sub = s.substring(i, i+1);
for(ArrayList<String> tuple : groups.get(i-1)) {
ArrayList<String> newTuple = new ArrayList<String>(tuple);
newTuple.add(sub);
newGroup.add(newTuple);
}
for(int j=i-1;j>=0;j--) {
if(s.charAt(i)==s.charAt(j) && (cache[i-1][j+1] || j>=i-2)) {
cache[i][j] = true;
ArrayList<ArrayList<String>> tmp = null;
sub = s.substring(j, i+1);
if(j==0) {
ArrayList<String> newTuple = new ArrayList<String>();
newTuple.add(sub);
newGroup.add(newTuple);
} else {
tmp = groups.get(j-1);
for(ArrayList<String> tuple : tmp) {
ArrayList<String> newTuple = new ArrayList<String>(tuple);
newTuple.add(sub);
newGroup.add(newTuple);
}
}
}
}
groups.put(i, newGroup);
}
return groups.get(s.length() - 1);
}
}
========
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null || s.isEmpty()) return res;
helper(s, 0, new ArrayList<>(), res);
return res;
}
private void helper(String s, int p, List<String> list, List<List<String>> res) {
if (p == s.length()) {
res.add(new ArrayList<>(list));
} else {
for (int i = p; i < s.length(); i++) {
String sub = s.substring(p, i + 1);
if (isPalin(sub)) {
list.add(sub);
helper(s, i + 1, list, res);
list.remove(list.size() - 1);
}
}
}
}
private boolean isPalin(String sub) {
int s = 0;
int e = sub.length() - 1;
while (s <= e) {
if (sub.charAt(s) == sub.charAt(e)) {
s++;
e--;
} else {
return false;
}
}
return true;
}
}
没有评论:
发表评论