[LeetCode] 131. 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"]
]

题意及分析:给出一个字符串,分割之后所有的子串都是回文串,求出所有可能的分割方法。

方法一:使用DFS方法查找,每次查找字符串头可能的回文串,然后切割掉,继续查找剩余的字符串s,如果最后s.length ==0 ,那么说明字符串可以全部分割为回文串,满足条件。添加到结果集中。

代码:

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        if(s==null || s.length() ==0 ) return res;
        //dfs??分割出每一个回文
        DFS(res,new ArrayList<String>(),s);
        return res;
    }
    private void DFS(List<List<String>> res ,List<String> arrayList,String s){
        if(s.length() == 0){
            res.add(new ArrayList<>(arrayList));
            return;
        }
        for(int i = 0;i<s.length();i++){
            String str = s.substring(0,i+1);
            if(isPalindrome(str)){
                arrayList.add(str);
                DFS(res,arrayList,s.substring(str.length()));
                arrayList.remove(arrayList.size()-1);
            }
        }

    }


    private boolean isPalindrome(String s ){        //判断s是否是回文
        for(int i = 0;i<s.length()/2;i++){
            if(s.charAt(i) != s.charAt(s.length()-1-i)) return false;
        }
        return true;
    }
}

 方法二:

//方法二:利用一个二维数组保存字符串的子串是否为回文,这样不用每次都去查找
    public List<List<String>> partition(String s) {
        List<List<String>> res = new ArrayList<>();
        if(s==null || s.length() ==0 ) return res;
        //dfs??分割出每一个回文
        boolean[][] isPalindrome =  new boolean[s.length()][s.length()];        //boolean[i][j]记录i到j是否为回文

        for(int i=0;i<s.length();i++){
            for(int j = 0;j<=i;j++){
                if(s.charAt(i)==s.charAt(j) && (i-j<=2||isPalindrome[j+1][i-1])){
                    isPalindrome[j][i] = true;
                }
            }
        }
        dfs(isPalindrome,res,new ArrayList<String>(),s,0);
        return res;
    }

    private void dfs( boolean[][] isPalindrome, List<List<String>> res,List<String> list,String s,int pos){
        if(pos == s.length()){
            res.add(new ArrayList<>(list));
            return;
        }

        for(int i = pos;i<s.length();i++){
            if(isPalindrome[pos][i]){
                list.add(s.substring(pos,i+1));
                dfs(isPalindrome,res,list,s,i+1);
                list.remove(list.size()-1);
            }
        }
    }

 

 

 

posted @ 2017-10-17 12:31  荒野第一快递员  阅读(246)  评论(0编辑  收藏  举报