My accepted Java code.


  • 0
    M

    I use s.length()+1 to store the result. This way, I can have a -1 at index 0 to avoid corner case.

        public int minCut(String s) {
            int[] result=new int[s.length()+1];
            result[0]=-1;//init index 0 to -1 so all string is palin will get -1+1=0
            int tmp=0,min=Integer.MAX_VALUE;
            boolean[][] palin=new boolean[s.length()][s.length()];
            for(int i=1;i<=s.length();i++){
                min=Integer.MAX_VALUE;
                for(int j=0;j<=i-1;j++){
                    if(s.charAt(j)==s.charAt(i-1)&&(i-j<=2||palin[i-2][j+1])){
                        palin[i-1][j]=true;
                        tmp=result[j]+1;
                        if(tmp<min) min=tmp;
                    }
                }
                result[i]=min;
            }
            return (s.length()==0)?0:result[s.length()];
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.