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

Palindrome Partitioning

时间:2014-10-06 12:19:50      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   os   ar   java   for   sp   div   

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 class Solution
{
    ArrayList<List<List<String>>> lists;

    String s;

    public boolean isPalindrome(int start, int end)
    {
        while (end > start)
        {
            if (s.charAt(end) != s.charAt(start))
            {
                return false;
            }
            end--;
            start++;
        }
        return true;
    }

    public void calPartition(int index)
    {
        List<List<String>> result=lists.get(index);
        for (int end = index; end < s.length(); end++ )
        {
            if(isPalindrome(index,end))
            {
                String pString=s.substring(index,end+1);
                if(end==s.length()-1)
                {
                    List<String>p=new LinkedList<String>();
                    p.add(pString);
                    result.add(p);
                    continue;
                }
                List<List<String>> p=lists.get(end+1);
                for(List<String>tmp:p)
                {
                    List<String> t=new LinkedList<String>();
                    t.addAll(tmp);
                    t.add(0, pString);
                    result.add(t);
                }
            }
        }
    }
    public List<List<String>> partition(String s)
    {
        lists= new ArrayList<List<List<String>>>(s.length());
        this.s = s;
        for (int i = 0; i < s.length(); i++ )
        {
            lists.add(new LinkedList<List<String>>());
        }
        for (int i = s.length()-1; i >=0; i-- )
        {
            calPartition(i);
        }
        return lists.get(0);
    }
}


Palindrome Partitioning

标签:style   color   io   os   ar   java   for   sp   div   

原文地址:http://blog.csdn.net/jiewuyou/article/details/39826513

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