palindrome-partitioning Java code

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<ArrayList<String>> partition(String s) {
    ArrayList<ArrayList<String>> lists = new ArrayList<>();
    ArrayList<String> list = new ArrayList<>();
    partitionHepler(lists, list, s);
    return lists;
  }

  public static void partitionHepler(ArrayList<ArrayList<String>> lists, ArrayList<String> 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;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值