分割回文字符串
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a"
输出:[["a"]]
public class Partition {
List<List<String>> result = new ArrayList<>();
List<String> path = new LinkedList<>();
public List<List<String>> partition(String s){
backTracking(s,0);
return result;
}
private void backTracking(String s, int startIndex){
if (startIndex>=s.length()){
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex;i<s.length();i++){
//判断回文
if (isPalindrome(s,startIndex,i)){
//进行分割
String str = s.substring(startIndex,i+1);
path.add(str);
}else {
continue;
}
//回溯递归纵向遍历
backTracking(s,i+1);
path.remove(path.size()-1);
}
}
//判断是否是回文串
private boolean isPalindrome(String s, int startIndex, int end) {
for (int i = startIndex, j = end; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}
//思路:
跟组合思路相似:
这里需要分割,需要横向遍历时,需要判断是否回文,来进行分割
这里分享一个回溯模版
void backtracking(参数) {
if (终止条件) {
存放结果;
return;
}
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
处理节点;
backtracking(路径,选择列表); // 递归
回溯,撤销处理结果
}
}