给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。
DFS
三个字符的字符串 例如:aab 有四种子串方案 a ab,aa b,a a b, aab 也就是两个数字1,2的所有可能组合 数字代表了对字符串的切割位置
然后就是一个判断子串是否为回文串 这里用一个二维数组去判断从字符串某一个字符开始(行)到某一个字符结束(列)的子串是否为回文串 构造这个二维数组利用了动态规划 即判断一个子串是回文串 它第一个字符和最后一个字符一定相同 并且去掉这两个字符也一定是回文串
class Solution {
private boolean[][] isPalindrome;
public List<List<String>> partition(String s) {
int n = s.length();
List<List<String>> results = new ArrayList<>();
List<String> combination = new ArrayList<>();
getPalindrome(s);
helper(s, 0, combination, results);
return results;
}
public void getPalindrome(String s){
int n = s.length();
isPalindrome = new boolean[n][n];
for(int i = 0; i < n; i++)
isPalindrome[i][i] = true;
for(int i = 0; i < n - 1; i++)
isPalindrome[i][i+1] = (s.charAt(i) == s.charAt(i+1));
for(int i = n - 3; i >=0; i--){
for(int j = i + 2; j < n; j++){
isPalindrome[i][j] = (isPalindrome[i+1][j-1] && (s.charAt(i) == s.charAt(j)));
}
}
}
public void helper(String s, int startIndex, List<String> combination, List<List<String>> results){
if(startIndex == s.length())
results.add(new ArrayList<>(combination));
for(int i = startIndex; i < s.length(); i++){
if(!isPalindrome[startIndex][i])
continue;
combination.add(s.substring(startIndex,i + 1));
helper(s, i + 1, combination, results);
combination.remove(combination.size() - 1);
}
}
}