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"] ]
the idea is to maintain the result from 0 to (i - 1), when the ith letter comes in, find all the palindrome end with ith letter, and start with jth letter, so the result is dp[j] with all List in dp[j] adding substring(j,i).
Code :
public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> dp[] = new List[s.length() + 1];
dp[0] = new ArrayList<>();
dp[0].add(new ArrayList<String>());
for(int i = 1 ; i < dp.length; i++){
dp[i] = new ArrayList<>();
for(int j = i ; j > 0 ;j--){
if(isPanlindrome(s,j-1,i-1)){
for(List<String> l : dp[j - 1]){
List<String> temp = new ArrayList<>(l);
temp.add(s.substring(j - 1, i));
dp[i].add(temp);
}
}
}
}
return dp[dp.length - 1];
}
public boolean isPanlindrome(String s, int start, int end){
while(start < end){
if(s.charAt(start) == s.charAt(end)){
start++;
end--;
} else {
return false;
}
}
return true;
}
}