2014年4月27日 星期日

[LeetCode] 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.
Solution:O(n*n)
public class Solution {
    public int minCut(String s) {
        char[] str = s.toCharArray();
        int len = s.length();
        boolean [][]isP = new boolean[len][len];
        int DP[] = new int[len+1];
        for(int t=0; t<DP.length;t++)
         DP[t] = len-t;
         
        for(int i =len-1; i>=0; i--){
         for(int j=i; j<len;j++){
          if(str[i] == str[j] && (j-i<2 ||  isP[i+1][j-1])){
           isP[i][j] = true;
           DP[i] = Math.min(DP[i], DP[j+1]+1);
          }
         }
        }
        return DP[0]-1;
    }
    
    public boolean isPal(String s){
        if(s.length() == 1){
         return true;
        }
        
        char str[] = s.toCharArray();
        for(int i=0; i< str.length/2; i++){
            if(str[i]!= str[str.length-1-i] ){
             return false;
            }
        }
        return true;
    }
}
Key Concept: Use two dimension array to solve DP  

沒有留言:

張貼留言