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 =
Return
"aab",Return
[
["aa","b"],
["a","a","b"]
]
Solution:
DFS transformation.
Hints: return all possible ... For "all" questions, it typically relates to DFS.
public class Solution {
public ArrayList> partition(String s) {
ArrayList> result = new ArrayList>();
ArrayList subset = new ArrayList();
helper(s, 0, result, subset);
return result;
}
public void helper(String s, int begin, ArrayList> result, ArrayList subset){
if(begin == s.length()){
result.add(new ArrayList(subset));
return;
}
for(int i = begin; i < s.length(); i++){
String str = s.substring(begin, i+1);
if (isPalindrome(str)){
subset.add(str);
helper(s, i+1, result, subset);
subset.remove(subset.size()-1);
}
}
}
public boolean isPalindrome(String str){
int l = 0;
int r = str.length() - 1;
while(l < r){
if(str.charAt(l) != str.charAt(r))
return false;
l++;
r--;
}
return true;
}
}
No comments:
Post a Comment