【leetcode刷题笔记】Palindrome Partitioning II

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.


 

题解:DP。

用dp[i]记录从[i,s.length]所需要的最少cut,则dp[i] = min(dp[i], dp[j+1]+1) (j=i,i+1,...,s.length)。

即如果s[i,j]是一个回文字符串,那么s[j+1,s.length]需要的最少cut,加上s[i,j]就可以得到一个cut。

如下图所示:

此题还有个坑是判断回文的时候,不能用单独的判断函数,而要在动态规划的过程中维护一个数组isPar[i][j]表示s[i,j]是否是字符串,因为我们只在s[i,j]是回文的时候才去看dp[j+1]并且得到一个cut,所以我们只需要在s(i) == s(j)的时候,利用isPar[i+1,j-1](或者j-i<2)做出s[i,j]是否是回文的判断。

代码如下:

 1 public class Solution {
 2     public int minCut(String s){
 3         if(s == null || s.length() == 0)
 4             return 0;
 5         int length = s.length();
 6         int[] dp = new int[length+1];
 7         boolean[][] isPar = new boolean[length][length]; 
 8         
 9         for(int i = length-1;i>=0;i--){
10             dp[i] = s.length() - i; 
11             for(int j = i;j<s.length();j++){
12                 //only if s[i] == s[j], s[i,j] may be a palindrome
13                 if(s.charAt(i)==s.charAt(j)){
14                     if(j-i<2 || isPar[i+1][j-1]){
15                         isPar[i][j] = true; 
16                         dp[i] = Math.min(dp[i], dp[j+1]+1);
17                     }
18                 }
19             }
20         }
21         return dp[0]-1;
22     }
23 }

 

posted @ 2014-07-26 16:01  SunshineAtNoon  阅读(342)  评论(0编辑  收藏  举报