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"] ]
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
if(s == null || s.length() == 0) return result;
ArrayList<String> list = new ArrayList<String>();
helper(s, result, list, 0);
return result;
}
private void helper(String s, ArrayList<ArrayList<String>> result, ArrayList<String> list, int start){
if(start == s.length()) result.add(new ArrayList<String>(list));
for(int i = start; i < s.length(); i++){
String current = s.substring(start, i + 1);
if(isPalindrome(current)){
list.add(current);
helper(s, result, list, i + 1);
list.remove(list.size() - 1);
}
}
}
private boolean isPalindrome(String s){
int beg = 0;
int end = s.length() - 1;
while (beg < end) {
if (s.charAt(beg) != s.charAt(end)) {
return false;
}
beg++;
end--;
}
return true;
}
}