Palindrome Partitioning Java

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"]
  ]


  Idea: Recursive-loop + dynamic programming + backtracking
    Combination of Longest Palindromic Substring & Word Break II
    There are two major steps:
    1.palindromic dictionary that using same method as Longest Palindromic Substring to get
    2. Use recursive-loop method to find palindrome partition
       add into subItem list if palindrome condition was satisfied
       Same approach as Work Break II


    Time: base on result size, can be exponent in worst case



public class Solution {
      public static ArrayList<ArrayList<String>> partition(String s) {
        ArrayList<ArrayList<String>> res=new ArrayList<ArrayList<String>>();
        if(s==null || s.length()==0) return res;
        boolean dict[][]=palinDict(s);
        helper(s,dict,0,res,new ArrayList<String>());
        return res;
    }
    //Recursive-loop
    private static void helper(String s,boolean[][] dict, int index,ArrayList<ArrayList<String>> res, ArrayList<String> subItem ){
        //Finish scanning the string
        if(index>=s.length()){
            res.add(new ArrayList<String>(subItem));
            return;
        }
        //recursive-loop
        for(int i=index;i<s.length();i++){
            //only deal with palindrome case
            if(dict[index][i]){
                subItem.add(s.substring(index,i+1));
                helper(s,dict,i+1,res,subItem);
                //backtracking
                subItem.remove(subItem.size()-1);
            }
        }

    }
    //Use method of dynamic programming
    private static boolean[][] palinDict(String s){
        int len=s.length();
        boolean[][] dict=new boolean[len][len];
        for(int i=len-1;i>=0;i--){
            for(int j=i;j<len;j++){
                //check for valid palindrome cae
                if(s.charAt(i)==s.charAt(j) && (j-i<2 || dict[i+1][j-1])){
                    dict[i][j]=true;
                }
            }
        }
        return dict;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值