代码1
DFS
Runtime: 3 ms, faster than 59.03% of Java online submissions for Palindrome Partitioning.
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList();
List<String> partition = new ArrayList();
dfs(s, 0, res, partition);
return res;
}
public void dfs(String s, int start, List<List<String>> res, List<String> partition) {
if (start == s.length()) {
res.add(new ArrayList(partition));
return;
}
for (int i = start; i < s.length(); i++) {
String substring = s.substring(start, i + 1);
if (!isPalindrome(substring)) continue;
partition.add(substring);
dfs(s, i + 1, res, partition);
partition.remove(partition.size() - 1);
}
}
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
}