Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
public class Solution {
public List<List<String>> partition(String s) {
List<String> cur = new ArrayList<>();
List<List<String>> result = new ArrayList<>();
partition(s.toCharArray(), 0, cur, result);
return result;
}
private void partition(char[] s, int start, List<String> cur, List<List<String>> result) {
if(start == s.length) {
result.add(new ArrayList<>(cur));
return;
}
StringBuilder str = new StringBuilder();
for(int i = start; i < s.length; i++) {
str.append(s[i]);
if(isPalindrome(str)){
cur.add(str.toString());
partition(s, i+1, cur, result);
cur.remove(cur.size() - 1);
}
}
return;
}
private boolean isPalindrome(StringBuilder str) {
int start = 0;
int end = str.length() - 1;
while(start <= end) {
if(str.charAt(start) != str.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}