码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]131 Palindrome Partitioning

时间:2015-01-18 18:36:06      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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

代码:

    public boolean isPalindrome(String s)
    {
        int len = s.length();
        if(len == 0)
            return true;
        int mid = (len-1)/2;
        for(int i =0; i <=mid; i++)
            if(s.charAt(i) != s.charAt(len-1-i))
                return false;
        return true;
    }
    public void getPartation(List<List<String>> result, List<String>list, List<List<Integer>> part,String s,int begin){
        if(list == null)
            list = new ArrayList<String>();
        if(begin == s.length()){
            result.add(list);
            return;
        }
        
        for(int i = 0; i < part.get(begin).size(); i++)
        {
            List<String> temp = new ArrayList<String>(list);
            int len = part.get(begin).get(i);
            temp.add(s.substring(begin,begin+len));
            getPartation(result,temp,part,s,begin+len);
        }
    }
    public List<List<String>> partition(String s) {
        int len = s.length();
        List<List<String>> result = new ArrayList<List<String>>();
        if(len == 0)
            return result;
        
        List<List<Integer>> part = new ArrayList<List<Integer>>();
        for(int i = 0; i<len; i++){
            List<Integer> list = new ArrayList<Integer>();
            for(int j = i+1; j <=len; j++)
            {
                String temp = s.substring(i,j);
                if(isPalindrome(temp))
                    list.add(j-i);
            }
            part.add(list);
        }
        List<String> list = null;
        getPartation(result,list,part,s,0);
        return result;
    }


[leetcode]131 Palindrome Partitioning

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/42836935

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