LeetCode-palindrome-partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s ="aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]
import java.util.ArrayList;
import java.util.List;
 
public class Solution {
  public static ArrayList> partition(String s) {
    ArrayList> lists = new ArrayList<>();
    ArrayList list = new ArrayList<>();
    partitionHepler(lists, list, s);
    return lists;
  }
 
  public static void partitionHepler(ArrayList> lists, ArrayList list, String s) {
    if (null == s || s.length() == 0) {
      lists.add(new ArrayList<>(list));
      return;
    }
    int len = s.length();
    for (int i = 0; i <= len;i++) {
      String subStr = s.substring(0, i);
      if (isPalindrome(subStr)) {
        list.add(subStr);
        partitionHepler(lists, list, s.substring(i, len));
        list.remove(list.size() - 1);
      }
    }
  }
 
  public static boolean isPalindrome(String s) {
    if (null == s || s.length() == 0) return false;
    int length = s.length();
    int middle = length / 2;
    for (int i = 0; i < middle;i++) {
      if (s.charAt(i) != s.charAt(length - 1 - i)) {
        return false;
      }
    }
    return true;
  }
}

 

你可能感兴趣的:(LeetCode)