[leedcode 132] 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.
public class Solution { /* dp[i][j]保存s(i,j)是否是回文,因为dp[i][j]=dp[i+1][j-1]&&s.charAt(i)==s.charAt(j)(j-i>=2时),即求dp[i][j]需要借助dp[i+1][j-1]求出,所以求dp时,需要从下往上,并且从左向右。 求出dp之后,需要构造一个res数组,res[i]保存从0到i需要剪切的最少个数。如果dp[0][i]是回文,res[i]=0,如果不是回文,此时已知res[0~i-1]已经求出,因此需要借助res[j](0<=j<i)求res[i]*/ public int minCut(String s) { if(s==null||s.length()<1) return 0; int len=s.length(); int res[]=new int[len]; boolean dp[][]=new boolean[len][len]; for(int i=len-1;i>=0;i--){ for(int j=i;j<len;j++){ if(s.charAt(i)==s.charAt(j)&&(j-i<2||dp[i+1][j-1])){ dp[i][j]=true; } } } for(int i=0;i<len;i++){ int ms=len; if(dp[0][i]){ res[i]=0; }else{ for(int j=0;j<i;j++){ if(dp[j+1][i]&&ms>res[j]+1) ms=res[j]+1; } res[i]=ms; } } return res[len-1]; } }