题目描述(中等难度)
给一个字符串,然后在任意位置切割若干次,保证切割后的每个字符串都是回文串。输出所有满足要求的切割结果。
解法一 回溯
public class Palindrome_Partitioning2 {
public static List<List<String>> partition(String s){
List<List<String>> res = new ArrayList<>();
helper(res,s,new ArrayList<>(),0);
return res;
}
private static void helper(List<List<String>> res, String s, List<String> temp, int start){
if(start == s.length()){
res.add(new ArrayList<>(temp));
return;
}
for(int i =start + 1;i <= s.length();i++){
if(isValid(s.substring(start,i))){
temp.add(s.substring(start,i));
helper(res,s,temp,i);
temp.remove(temp.size()-1);
}
}
}
private static boolean isValid(String s){
int left = 0;
int right = s.length() - 1;
while(left < right){
if(s.charAt(left) != s.charAt(right)) return false;
left ++;
right --;
}
return true;
}
public static void main (String args[]){
String s ="aabb";
List<List<String>> ans = partition(s);
System.out.println(ans);
}
}
参考文献
- https://www.youtube.com/watch?v=dl1gtKWXKEs