码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 131. Palindrome Partitioning Java

时间:2017-10-17 15:02:23      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:code   回文串   部分   length   str   turn   代码   题目   remove   

题目:

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;
    }
}

 

 

 

[LeetCode] 131. Palindrome Partitioning Java

标签:code   回文串   部分   length   str   turn   代码   题目   remove   

原文地址:http://www.cnblogs.com/271934Liao/p/7681024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!