一个人的朝圣 — LeetCode打卡第26天
知识总结
今天做了两道组合问题在昨天已经写了, 重点讲一下切割问题
Leetcode 131. 分割回文串
题目说明
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串
代码说明
这道题其实很考验如何将问题转化
第一步: 运用双指针写出如何判断回文串的方法
第二部, 理解回溯的过程.
参照下面这幅图.
class Solution {
List<List<String>> res = new ArrayList<>();
LinkedList<String> path = new LinkedList<>();
public List<List<String>> partition(String s) {
backtrack(s, 0);
return res;
}
public void backtrack(String s, int startIndex){
if(startIndex == s.length()){
res.add(new ArrayList<>(path));
}
for(int i = startIndex; i< s.length(); i++){
if(isPalidrome(s, startIndex, i)){
String str = s.substring(startIndex, i+1);
path.add(str);
backtrack(s, i+1);
path.removeLast();
}
}
}
public boolean isPalidrome(String s, int startIndex, int end){
while(startIndex < end){
if(s.charAt(startIndex++) != s.charAt(end--)){
return false;
}
}
return true;
}
}