131. Palindrome Partitioning
Medium
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ]
class Solution {
public List<List<String>> partition(String s) {
if (null == s || s.length() < 1) {
return new ArrayList();
}
int n = s.length();
if (1 == s.length()) {
return Arrays.asList(Arrays.asList(s));
}
char[] sc = s.toCharArray();
boolean[][] bc = new boolean[n][n];
for (int i = 0; i < n - 1; i++) {
bc[i][i] = true;
if (sc[i] == sc[i + 1]) {
bc[i][i + 1] = true;
}
}
bc[n - 1][n - 1] = true;
// i indicates string length
for (int i = 3; i <= n; i++) {
// j indicates string index
for (int j = 0; j <= n - i; j++) {
boolean b = (sc[j] == sc[j + i - 1]);
bc[j][j + i - 1] = b && bc[j + 1][j + i - 1 - 1];
}
}
List<List<String>> result = new ArrayList<>();
buildPalindrome(bc, result, new Stack<>(), s, 0, n);
return result;
}
private void buildPalindrome(boolean[][] bc,
List<List<String>> result, Stack<String> stack,
String s, int depth, int n) {
if (n == depth) {
result.add(new ArrayList(stack));
return;
}
for (int i = depth; i < n; i++) {
if (bc[depth][i]) {
stack.push(s.substring(depth, i + 1));
buildPalindrome(bc, result, stack, s, i + 1, n);
stack.pop();
}
}
}
}