Palindrome Partitioning Java

来源:互联网 发布:二极管功耗计算软件 编辑:程序博客网 时间:2024/04/29 01:11

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
原创粉丝点击