Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example
Given s = "aab"
, return:
[
["aa","b"],
["a","a","b"]
]
分析:递归法。
public class Solution {
/**
* @param s: A string
* @return: A list of lists of string
*/
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<List<String>>();
if(s.length() == 0) return res;
helper(res, new ArrayList<String>(), s, 0);
return res;
}
void helper(List<List<String>> res, List<String> list, String s, int index) {
if(index >= s.length()) {
res.add(new ArrayList<String>(list));
return;
}
for(int i = index; i < s.length(); i++) {
if(valid(s, index, i)) {
String str = s.substring(index, i + 1);
list.add(str);
helper(res, list, s, i + 1);
list.remove(list.size() - 1);
}
}
}
boolean valid(String s, int start, int end) {
if(start > end) return false;
else {
while(start < end) {
if(s.charAt(start) == s.charAt(end)) {
start++;
end--;
} else {
return false;
}
}
}
return start >= end;
}
}