131. Palindrome Partitioning
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]public class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
helper(res, s, new ArrayList<>(), 0);
return res;
}
private void helper(List<List<String>> res, String s, List<String> curr, int start) {
if (start == s.length()) {
res.add(new ArrayList<>(curr));
return;
}
for (int i = start + 1; i <= s.length(); i++) {
String sub = s.substring(start, i);
if (isPal(sub)) {
curr.add(sub);
helper(res, s, curr, i);
curr.remove(curr.size() - 1);
}
}
}
private boolean isPal(String str) {
int l = 0, r = str.length() - 1;
while (l < r) {
if (str.charAt(l) != str.charAt(r)) return false;
l++;
r--;
}
return true;
}
}Last updated