Guest User

Untitled

a guest
Mar 21st, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. class Solution {
  2. public List<List<String>> partition(String s) {
  3. List<List<String>> res = new ArrayList<>();
  4. backtrack(res, new ArrayList<String>(), 0, s);
  5. return res;
  6. }
  7.  
  8. private void backtrack(List<List<String>> res, List<String> path, int index, String s) {
  9. if (index == s.length()) {
  10. res.add(new ArrayList<String>(path));
  11. return;
  12. }
  13.  
  14. for (int i = index; i < s.length(); i++) {
  15. if (isPalindrome(s.substring(index, i + 1))) {
  16. path.add(s.substring(index, i + 1));
  17. backtrack(res, path, i + 1, s);
  18. path.remove(path.size() - 1);
  19. }
  20. }
  21. }
  22.  
  23. private boolean isPalindrome(String s) {
  24. char[] arr = s.toCharArray();
  25. int l = 0;
  26. int r = arr.length - 1;
  27.  
  28. while (l < r) {
  29. if (arr[l] != arr[r]) return false;
  30. l++;
  31. r--;
  32. }
  33.  
  34. return true;
  35. }
  36. }
Add Comment
Please, Sign In to add comment