Palindrome Partitioning

这道题是典型的深度优先搜索的问题, 可以多拿出来看看,和我之前做的subset以及permutation不一样的是这道题其实是排列组合中如何切数组的问题
[a,a,a,a]-- [a|a|a|a] -> [a|a|aa] -> [a|aa|a] -> [a|aaa] ->[aa|a|a] ->[aa|aa] -> [aaa|a] ->[aaaa]

在这个基础上,每一次加到本层的list的时候需要判断是不是回文的(这里不需要判断大小写还有有没有别的字符),同时如果s的长度达到的时候,我们就有一个结果。 

 

public class Solution {
    /**
     * @param s: A string
     * @return: A list of lists of string
     */
    public List<List<String>> partition(String s) {
        // write your code here
        List<List<String>> result = new ArrayList<List<String>>();
        if("".equals("s")){
            return result;
        }
        List<String> list = new ArrayList<String>();
        helper(result, list, s, 0);
        return result;
    }
    
    private void helper(List<List<String>> result, List<String> list, 
                        String s, int pos){
        if(pos == s.length()){
            result.add(new ArrayList<String>(list));
            return;
        }
        
        for(int i = pos; i < s.length(); i++){
            String sub = s.substring(pos, i+1);
            if(!isPalindrome(sub)){
                continue;
            }
            list.add(sub);
            helper(result, list, s, i+1);
            list.remove(list.size() -1);
        }
    }
    
    private boolean isPalindrome(String s){
        int low = 0;
        int high = s.length() - 1;
        while(low < high){
            if(s.charAt(low) != s.charAt(high)){
                return false;
            }
            low++;
            high--;
        }
        return true;
    }
}

 

posted on 2016-08-19 09:25  codingEskimo  阅读(198)  评论(0编辑  收藏  举报

导航