public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>> ();
ArrayList<String> temp = new ArrayList<String> ();
dfs(s, temp, res);
return res;
}
public void dfs(String s, ArrayList<String> temp, ArrayList<ArrayList<String>> res) {
if (s.length()==0) {
res.add((ArrayList<String>) temp.clone());
return;
}
for (int i=1; i<=s.length(); i++) {
String substr = s.substring(0, i);
if (isPalindrome(substr)) {
temp.add(substr);
dfs(s.substring(i), temp, res);
temp.remove(temp.size()-1);
}
}
}
public boolean isPalindrome(String s) {
int i=0;
int j=s.length()-1;
while (i<j) {
if (s.charAt(i)!=s.charAt(j)) return false;
i++;
j--;
}
return true;
}
}
没有评论:
发表评论