给你一个字符串 s,请你将 **s **分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
示例 1:
输入: s = "aab"
输出: [["a","a","b"],["aa","b"]]
示例 2:
输入: s = "a"
输出: [["a"]]
提示:
1 <= s.length <= 16s仅由小写英文字母组成
题解:
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
partition(s, 0, 0, new ArrayList<>(), res);
return res;
}
public void partition(String s, int start, int end, List<String> tempRes, List<List<String>> res) {
//如果分隔起点超出了字符串长度,说明已经分隔完,直接将结果返回
if (start == s.length()) {
res.add(new ArrayList<>(tempRes));
return;
}
//如果分隔终点超出了字符串,直接返回
if (end == s.length()) {
return;
}
//当前不进行拆分,直接将end+1
partition(s, start, end + 1, tempRes, res);
//当前进行拆分
String part = s.substring(start, end + 1);
//是回文字符串,加入到结果中
if (isPalindrome(part)) {
tempRes.add(part);
//start和end更新为分隔部分的下一个字符
partition(s, end + 1, end + 1, tempRes, res);
//回溯
tempRes.remove(tempRes.size() - 1);
}
}
private boolean isPalindrome(String s) {
int start =0;
int end = s.length() - 1;
while (start <= end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}