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 List<List<String>> partition(String s) {
int n=s.length();
List<List<String>> results= new ArrayList<List<String>>();
List<String> result= new ArrayList<String>();
dfs(results, result, 0, s);
return results;
}
void dfs(List<List<String>> results, List<String> result, int index, String s){
if(index>=s.length()){
results.add(new ArrayList<String>(result));
}
for(int i=index;i<s.length();i++){
String temp=s.substring(index,i+1);
if(isPalindrome(temp)){
result.add(temp);
dfs(results, result, i+1, s);
result.remove(result.size()-1);
}
}
}
public boolean isPalindrome(String s){
if(s==null) return false;
int pa=0;
int pb=s.length()-1;
while(pa<=pb){
if(s.charAt(pa)!=s.charAt(pb)){
return false;
}
pa++;
pb--;
}
return true;
}