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

[LeetCode]131 Palindrome Partitioning

时间:2015-01-08 15:30:19      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/palindrome-partitioning/

http://blog.csdn.net/linhuanmars/article/details/22777711

public class Solution {
    public List<List<String>> partition(String s) {
        
        List<List<String>> result = new ArrayList<>();
        
        if (s == null || s.isEmpty())
            return result;
        
        boolean[][] dict = buildDict(s);
        help(s, dict, 0, new ArrayList<String>(), result);
        return result;
    }
    
    private void help(String s, boolean[][] dict, int start, List<String> item, List<List<String>> result)
    {
        if (start >= s.length())
        {
            result.add(new ArrayList<String>(item));
            return;
        }
        
        for (int i = start; i < s.length() ; i ++)
        {
            if (!dict[start][i])
                continue;

            item.add(s.substring(start, i + 1));
                
            help(s, dict, i + 1, item, result);
                
            item.remove(item.size() - 1);
        }
    }
    
    // dict[i][j] means substring(i, j + 1) is palin
    // dict(i, j) = char[i] == char[j] && dict(i + 1, j - 1)
    // So i starts from s.length to 0
    // j starts from i to s.length
    private boolean[][] buildDict(String s)
    {
        int len = s.length();
        boolean[][] dict = new boolean[len][len];
        
        for (int i = len - 1 ; i >= 0 ; i --)
        {
            for (int j = i ; j < len ; j ++)
            {
                if (i == j)
                    dict[i][j] = true;
                else if(i + 1 == j)
                    dict[i][j] = s.charAt(i) == s.charAt(j);
                else
                    dict[i][j] = s.charAt(i) == s.charAt(j) && dict[i + 1][j - 1];
            }
        }
        
        return dict;
    } 
}


[LeetCode]131 Palindrome Partitioning

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600690

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