132. Palindrome Partitioning II

2016-06-29  本文已影响0人  HalcyonMoon

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.
public class Solution {
    public int minCut(String s) {
        int len = s.length();
        if(len == 0){
            return 0;
        }
        char sc[] = s.toCharArray();
        boolean palindrome[][] = new boolean[len][len];
        int partition[] = new int[len+1];
        partition[len] = 0;
        for(int i=len-1; i>=0; i--){
            partition[i] = len-i;
            for(int j=i; j<len; j++){
                if(i==j || sc[i]==sc[j] && (i+1==j || palindrome[i+1][j-1])){
                    palindrome[i][j] = true;
                    partition[i] = Math.min(partition[i], partition[j+1]+1);
                }
            }
        }
        
        return partition[0]-1;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读