Sunday, August 3, 2014

Palindrome Partition II

This question is similar to the "palindrome partition I", but easier than that one, since we only need to care about minCut, rather than these possible ways to cut, which takes more spaces.  Dictionary is also necessary. Explanation can be found in the for loop.

BTW, the commented code in minCut(String s) is my previous version. This version can get same result, but it takes more time, which should be O(n^3), thus I get TLE.

Anyway, thanks to code_ganker's good post about "palindrome partition I".

public class Solution {
    public int minCut(String s) {
        if(s == null || s.length() <= 1) return 0;
        
        boolean[][] dict = buildDict(s);
        // int minNum = Integer.MAX_VALUE;
        // for(int i = 0; i < s.length(); i++){ 
        //     if(minNum == 0) return 0;
        //     minNum = Math.min(minNum,i + minCut(s,dict,i));
            
        // }
        // return minNum;
        int[] res = new int[s.length() + 1];
        res[0] = 0;
        for(int i = 0; i < s.length(); i++){
            res[i+1] = i+1;
            for(int j = 0; j <= i; j++){
                if(dict[j][i]) res[i+1] = Math.min(res[i+1],res[j]+1);// be careful, it's dict[j][i],
                // if dict[j][i] true, add one to res[j], i.e. add a new cut based on previous result
            }
        }
        return res[s.length()] - 1;
    }
    
    public boolean[][] buildDict(String s){
        boolean[][] dict = new boolean[s.length()][s.length()];
        
        for(int i = s.length() - 1; i >= 0 ; i --){
            for(int j = i; j < s.length(); j ++){
                if(s.charAt(i)==s.charAt(j) && ((j-i<2)||dict[i+1][j-1])){// briliant method by code ganker
                    dict[i][j] = true;
                }
            }
        }
        return dict;
    }
    public int minCut(String s, boolean[][] dict, int startIdx){

        int tmpCut = Integer.MAX_VALUE;
        
        for(int i = s.length() - 1; i >= startIdx; i --){
            
            if(dict[startIdx][i]){
                if(i == s.length() - 1) return 0;
                tmpCut = Math.min(tmpCut, minCut(s,dict,i+1) + 1);
            }
        }
        return tmpCut;
    }
}

No comments:

Post a Comment