题目描述:
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
题目链接:LeetCode-131-分割回文串
代码实现:
class Solution {
List<List<String>> res = new LinkedList<>();
List<String> path = new ArrayList<>();
public List<List<String>> partition(String s) {
backTracking(s, 0);
return res;
}
public void backTracking(String s, int startIndex){
// 终止条件:startIndex就是切割线,当到达字符串末尾也就结束
if (startIndex >= s.length()){// 因为 s.substring要取到最后一个元素时会+1,所以这里的符号要包括 >
res.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < s.length(); i++) {
if (isPal(s.substring(startIndex,i+1))){// 判断当前的分支是否是回文串
path.add(s.substring(startIndex,i+1));
}else {
continue;
}
backTracking(s, i+1);// 递归
path.remove(path.size()-1);// 回溯
}
}
public boolean isPal(String s){
if (s.length()==1){
return true;
}
for (int i = 0,j=s.length()-1; i <=j; i++,j--) {
if (s.charAt(i) != s.charAt(j)){
return false;
}
}
return true;
}
}