![在这里插入图片描述](https://img-blog.csdnimg.cn/dfb8db3702f34de59605bff9ac51bb22.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAYmFqMDAx,size_20,color_FFFFFF,t_70,g_se,x_16)
原题链接
- 实现分割字符串,使用回溯
- 首先定义全局变量lists和deque用于保存结果
- 定义回溯函数backTracking
- 终止条件:当传入的开始位置索引大于等于字符串的长度的时候,将deque进行保存
- 之后是回溯的模板:首先定义for循环开始时,先判断是不是回文串(需要另外定义isPalindrome函数),若是则,使用substring来截取相应的字符,然后addlast进入deque。需要注意substring函数截取的字符串包括开始的位置,但是不包括截止的位置
- 然后重新进入回溯函数,此时的开始位置索引要进行+1
- 最后执行撤销removelast
- 在判断是否是回文串的isPalindrome函数中,使用双指针来进行判断
- 二刷:在for循环中,若判断是回文串的话,然后就截取当前的str,addLast 进入deque中,反之则continue,之后调用递归函数操作 i + 1 的位置, 递归之后执行deque 的撤销
- 在递归中,要移动到下一个位置,则 是 i + 1 的位置,而不是 begin + 1的位置
- substring 方法 中 只有两个参数(开始位置,结束位置 + 1)
- 截止条件是 当begin(开始位置)越界的情况出现时,则将path 保存 到res中
class Solution {
List<List<String>> res = new ArrayList<>();
Deque<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
if(s == null || s.length() == 0) return res;
recur(s, 0);
return res;
}
public void recur(String s, int begin){
if(begin >= s.length()){
res.add(new ArrayList<>(path));
return;
}
for(int i = begin; i < s.length(); i++){
if(judge(s, begin, i)){
String str = s.substring(begin, i + 1);
path.addLast(str);
}else{
continue;
}
recur(s, i + 1);
path.removeLast();
}
}
public boolean judge(String s, int start, int end){
for(int i = start, j = end; i < j; i++, j--){
if(s.charAt(i) != s.charAt(j)){
return false;
}
}
return true;
}
}
class Solution {
List<List<String>> lists = new ArrayList<>();
Deque<String> deque = new LinkedList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return lists;
}
private void backTracking(String s, int startIndex) {
if (startIndex >= s.length()) {
lists.add(new ArrayList(deque));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isPalindrome(s, startIndex, i)) {
String str = s.substring(startIndex, i + 1);
deque.addLast(str);
} else {
continue;
}
backTracking(s, i + 1);
deque.removeLast();
}
}
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;
}
}