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。

如下图所示:

【leetcode刷题笔记】Palindrome Partitioning II

此题还有个坑是判断回文的时候,不能用单独的判断函数,而要在动态规划的过程中维护一个数组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 }

 

相关文章:

  • 2021-11-15
  • 2022-12-23
  • 2021-08-04
  • 2021-11-04
  • 2021-04-05
  • 2022-01-07
  • 2021-09-23
猜你喜欢
  • 2022-12-23
  • 2022-01-18
  • 2022-01-29
  • 2022-02-24
  • 2021-12-02
  • 2021-09-24
  • 2022-01-12
相关资源
相似解决方案