Palindrome Partitioning II

来源:互联网 发布:mac不识别u盘启动 编辑:程序博客网 时间:2024/04/26 08:27
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.

还是用DP。在讨论区里看到一哥们的判断回文的算法,很好。用一个数组保存从首字符到所有字符的最小切割次数,注意要从-1开始。
Solution:
public class Solution {
    public int minCut(String s) {
     int slen = s.length();
     boolean[][] palind = new boolean[slen][slen];
        
     for(int i=slen-1;i>=0;i--)
     {
         for(int j=i;j<slen;j++)
         {
         palind[i][j] = (s.charAt(i)==s.charAt(j))&&((j-i<2)||palind[i+1][j-1]);
         }
      }
        
      int[] minCut = new int[slen+1];
        
      for(int i=0;i<slen+1;i++)
         minCut[i] = i-1;


      for(int i=0;i<slen;i++)
      {
         for(int j=i;j<slen;j++)
         {
             if(palind[i][j]&&minCut[i]<minCut[j+1])
             {    
                 minCut[j+1] = minCut[i]+1; 
             }
         }
      }
      return minCut[slen];
   }
}
0 0
原创粉丝点击