Advertisement
1988coder

Palindrome Partitioning I

Sep 16th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. class Solution {
  2.     public List<List<String>> partition(String s) {
  3.         List<List<String>> result = new ArrayList<>();
  4.         if (s == null) {
  5.             return result;
  6.         }
  7.         if (s.length() == 0) {
  8.             result.add(new ArrayList<String>());
  9.             return result;
  10.         }
  11.        
  12.         backtrack(result, new ArrayList<String>(), s, 0);
  13.        
  14.         return result;
  15.     }
  16.    
  17.     public void backtrack(List<List<String>> list, ArrayList<String> tempList, String s, int start) {
  18.         if (start == s.length()) {
  19.             list.add(new ArrayList<String>(tempList));
  20.             return;
  21.         }
  22.         for (int i = start; i < s.length(); i++) {
  23.             if (isPalindrome(s, start, i)) {
  24.                 tempList.add(s.substring(start, i+1));
  25.                 backtrack(list, tempList, s, i + 1);
  26.                 tempList.remove(tempList.size() - 1);
  27.             }
  28.         }
  29.     }
  30.    
  31.     public boolean isPalindrome (String s, int start, int end) {
  32.         if (start == end) {
  33.             return true;
  34.         }
  35.         while (start < end) {
  36.             if (s.charAt(start++) != s.charAt(end--)) {
  37.                 return false;
  38.             }
  39.         }
  40.         return true;
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement