Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
public class Solution {
/** * @param s: A string * @return: A list of lists of string */
public List<List<String>> partition(String s) {
List<List<String>> results = new ArrayList<>();
if (s == null || s == "") {
return results;
}
ArrayList<String> result = new ArrayList<>();
dfsHelper(s, 0, results, result);
return results;
}
private void dfsHelper(String s,
int start,
List<List<String>> results,
ArrayList<String> result) {
if (start == s.length()) {
results.add(new ArrayList<String>(result));
}
//判断清楚是对i、还是index进行递归!!!
for (int i = start; i < s.length(); i++) {
String subString = s.substring(start, i + 1);
if (!isPalindrome(subString)) {
continue;
}
result.add(subString);
dfsHelper(s, i + 1, results, result);
result.remove(result.size() - 1);
}
}
private boolean isPalindrome(String s) {
int start = 0;
int end = s.length() - 1;
while (start < end) {
if (s.charAt(start) != s.charAt(end)) {
return false;
}
start++;
end--;
}
return true;
}
}