1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public List<List<String>> partition(String s) { List<List<String>> resultList = new ArrayList<>(); List<String> subStrList = new ArrayList<>(); backtrack(resultList, subStrList, s, 0); return resultList; }
private void backtrack(List<List<String>> resultList, List<String> subStrList, String s, int startIndex) { if (startIndex == s.length()) { resultList.add(new ArrayList<>(subStrList)); return; }
for (int endIndex = startIndex; endIndex < s.length(); endIndex++) { if (isPalindrome(s, startIndex, endIndex)) { subStrList.add(s.substring(startIndex, endIndex + 1)); backtrack(resultList, subStrList, s, endIndex + 1); subStrList.remove(subStrList.size() - 1); } } }
private boolean isPalindrome(String s, int startIndex, int endIndex) { while (startIndex < endIndex) { if (s.charAt(startIndex++) != s.charAt(endIndex--)) { return false; } } return true; } }
|