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

Palindrome Partitioning

时间:2014-08-14 16:47:18      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:数据结构   算法   

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 {
    public List<List<String>> partition(String s) {
        List<List<String>> result=new LinkedList<List<String>>();
        LinkedList<String> output=new LinkedList<String>();
        dfs(s,0,output,result);
        return result;
    }
    public void dfs(String s,int start,LinkedList<String> output,List<List<String>> result){
        if(start==s.length()){
            List<String> list=new LinkedList<String>();
            list.addAll(output);
            result.add(list);
            return;
        }
        for(int i=start;i<s.length();i++){
            if(isPalindrome(s,start,i)){
                output.add(s.substring(start,i+1));
                dfs(s,i+1,output,result);
                output.pollLast();
            }
        }
    }
    public boolean isPalindrome(String s,int i,int j){
        while(i<=j){
            if(s.charAt(i)==s.charAt(j)){
                i++;
                j--;
            }
            else return false;
        }
        return true;
    }
}

Palindrome Partitioning,布布扣,bubuko.com

Palindrome Partitioning

标签:数据结构   算法   

原文地址:http://blog.csdn.net/dutsoft/article/details/38559529

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