136. 分割回文串
给定字符串
s
, 需要将它分割成一些子串, 使得每个子串都是回文串.
返回所有可能的分割方案.
样例
样例 1:
输入: "a"
输出: [["a"]]
解释: 字符串里只有一个字符, 也就只有一种分割方式 (就是它本身)
样例 2:
输入: "aab"
输出: [["aa", "b"], ["a", "a", "b"]]
解释: 有两种分割的方式.
1. 将 "aab" 分割成 "aa" 和 "b", 它们都是回文的.
2. 将 "aab" 分割成 "a", "a" 和 "b", 它们全都是回文的.
注意事项
-
不同的方案之间的顺序可以是任意的.
-
一种分割方案中的每个子串都必须是 s 中连续的一段.
public class Solution {
/*
* @param s: A string
* @return: A list of lists of string
*/
List<List<String>> sum = new ArrayList<>();
public List<List<String>> partition(String s) {
// write your code here
helper(s, 0, s.length() ,new ArrayList<String>());
return sum;
}
private void helper(String s, int start, int end,List<String> list) {
// System.out.println(start+","+end);
if (start>=end){
// System.out.println(start+","+end);
sum.add(new ArrayList<>(list));
return;
}
for (int i = end; i > start; i--) {
if (checkString(s, start, i -1)){
String temp=s.substring(start,i);
list.add(temp);
// System.out.println(temp);
helper(s, i, end,list);
list.remove(list.size()-1);
}
}
}
private boolean checkString(String s, int start, int end) {
if (start > end) return true;
if (s.charAt(start) == s.charAt(end)) {
return checkString(s, start + 1, end - 1);
} else {
return false;
}
}
}