131 Palindrome Partitioning
Given a strings, partition_s _such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning ofs.
Example:
Input:
"aab"
Output:
[
["aa","b"],
["a","a","b"]
]
Backtracking
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> ans = new ArrayList<>();
if (s == null || s.length() == 0) {
return ans;
}
List<String> part = new ArrayList<>();
helper(ans, part, 0, s);
return ans;
}
public void helper(List<List<String>> ans, List<String> part, int startIdx, String s) {
if (startIdx == s.length()) {
ans.add(new ArrayList<>(part));
}
for(int i = startIdx; i < s.length(); i++) {
String str = s.substring(startIdx, i + 1);
if(!isPalindrome(str)) {
continue;
}
part.add(str);
helper(ans, part, i + 1, s);
part.remove(part.size() - 1);
}
}
public boolean isPalindrome(String s) {
int start = 0;
int end = s.length() - 1;
// abba
//aba
while (start < end){
if (s.charAt(start) == s.charAt(end)) {
start++;
end--;
}else {
return false;
}
}
return true;
}
}