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<List<String>> result = new ArrayList<List<String>>();
List<String> path = new ArrayList<String>();
if(s == null || s.length() == 0){
return result;
}
helper(s,result,path,0);
return result;
}
private boolean isPalindrome(String s){
int start = 0;
int end = s.length() - 1;
while(start < end){
if(s.charAt(start) != s.charAt(end)) return false;
start++;
end--;
}
return true;
}
private void helper(String s,List<List<String>> result,List<String> path, int position){
if(position == s.length()){
result.add(new ArrayList<String>(path));
}
for(int i = position+1; i <= s.length(); i++){
String prefix = s.substring(position,i);
if(!isPalindrome(prefix)){
continue;
}
path.add(prefix);
helper(s,result,path,i);
path.remove(path.size()-1);
}
}
}