[LeetCode]132 Palindrome Partitioning II

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

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

public class Solution {
    public int minCut(String s) 
    {
        if(s == null || s.isEmpty())  
            return 0;

        // Building a dict
        boolean[][] dict = buildDict(s);
        
        // result[i] means from s[0,i], the min cut
        int[] result = new int[s.length() + 1];
        result[0] = 0;
        for (int i = 0 ; i < s.length() ; i ++)
        {
            result[i + 1] = i + 1; // max cut: single char cut
            for (int j = 0 ; j <= i ; j ++)
            {
                if (dict[j][i])
                {
                    result[i + 1] = Math.min(result[i + 1], result[j] + 1);
                }
            }
        }
        
        return result[result.length - 1] - 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)