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"]
]
public class Solution {
public ArrayList<ArrayList<String>> partition(String s) {
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
if (s == null || s.length() == 0) {
list.add(new ArrayList<String>());
return list;
}
helper(s, list, new ArrayList<String>(), 0, s.length());
return list;
}
public void helper(String s, ArrayList<ArrayList<String>> r, ArrayList<String> temp, int pos, int n) {
if (pos == n) {
ArrayList<String> newTemp = new ArrayList<String>(temp);
r.add(newTemp);
return;
}
// here we need an end pointer to extract each substrings
for (int end=pos+1; end<=n; end++) {
String sub = s.substring(pos, end);
if (isPalindrome(sub)) {
temp.add(sub);
helper(s, r, temp, end, n);
temp.remove(temp.size()-1);
}
// here you do not need to deal with the case that sub is not palindorme
}
}
public boolean isPalindrome(String string) {
if (string == null || string.length()==0)
return true;
boolean b = true;
int i=0, j=string.length()-1;
while (i <= j) {
if (string.charAt(i) != string.charAt(j))
b = false;
i++;
j--;
}
return b;
}
}
No comments:
Post a Comment