132. Palindrome Partitioning II

Problem:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

Analysis:
6/2/2018 update:
When j == 0 and isPalindrome[j][i] == true. It means no cut is needed.
--------------------------------------------------------------------------------------------------------------------------------------------
如果在j - i 范围内是palindrome, 那么0 ~ i 的其中一个cut数就是cut[j - 1] + 1. 
a a b b  
       j  i
j - i是bb, cut[j - 1] == 0, 那么cut[i] == 1 && j == 2. j 是从 0 ~ i 的,在遍历过程中更新最小cut就好了。
Solution:


class Solution {
    public int minCut(String s) {
        if (s == null || s.length() == 0)
            return 0;
        int len = s.length();
        int[] cut = new int[len];
        boolean[][] isPalindrome = new boolean[len][len];

        for (int i = 0; i < len; i++) {
            int min = i;
            for (int j = 0; j <= i; j++) {
                if (s.charAt(i) == s.charAt(j) && (i - j < 2 || isPalindrome[j + 1][i - 1])) {
                    isPalindrome[j][i] = true;
                    min = j == 0 ? 0 : Math.min(min, cut[j - 1] + 1);
                }
            }
            cut[i] = min;
        }
        return cut[len - 1];
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List