题目链接
思路
- 这道题同样可以分为很多步,我们用index来标明当前应该处理的子字符串开头是什么
- 对于这一步来说 我们应该查找以所有回文子字符串 然后继续调用helper函数~ 递归处理即可
class Solution {
List<List<String>> result;
String str;
public String[][] partition(String s) {
result = new ArrayList();
str = s;
helper(0, new ArrayList<>());
String[][] arrayResult = new String[result.size()][0];
for (int i = 0; i < result.size(); i++) {
arrayResult[i] = result.get(i).toArray(new String[0]);
}
return arrayResult;
}
public boolean isPalindrome(int start, int end) {
while (start < end) {
if (str.charAt(start) == str.charAt(end)) {
start++;
end--;
} else
return false;
}
return true;
}
private void helper(int start, List<String> partition) {
if (start == str.length())
result.add(new ArrayList<>(partition));
else if (start < str.length()) {
for (int i = start; i < str.length(); i++) {
if (isPalindrome(start, i)) {
partition.add(str.substring(start, i + 1));
helper(i + 1, partition);
partition.remove(partition.size() - 1);
}
}
}
}
}