分割回文串
题目:
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
解题思路:首先创建一个数组记录i到j是否为回文,之后用dfs进行回溯
class Solution {
public List<List<String>> partition(String s) {
if(s == null)
return null;
List<List<String>> ans = new ArrayList();
if(s.isEmpty())
return ans;
char[] ch = s.toCharArray();
int len = ch.length;
boolean isPail[][] = new boolean[len][len];
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
isPail[j][i] = check(ch, j, i);
// System.out.println("i = " + j + ", j = " + i + ", dp = " + isPail[j][i]);
}
}
Deque<String> list = new LinkedList();
dfs(0, len, list, isPail, ans, s);
return ans;
}
private void dfs(int start, int len, Deque<String> path, boolean[][] dp, List<List<String>> res, String s) {
if (start == len) {
res.add(new ArrayList<>(path));
return;
}
for (int i = start; i < len; i++) {
if (!dp[start][i]) {
continue;
}
path.addLast(s.substring(start, i + 1));
dfs(i + 1, len, path, dp, res, s);
path.removeLast();
}
}
private boolean check(char[] ch, int i, int j) {
while(i < j && ch[i] == ch[j]) {
i++;
j--;
}
return i >= j;
}
}