Given a string s, divide s into substrings so that each substring is a palindrome.
Returns the minimum number of split times that s meets the requirements.
Sample Example
For example, give the string s = "AaB",
Returns 1 because a split can divide the string s into ["AA", "B"] so that two palindrome strings
Import Java.util.Scanner;
/** * Given a string s, divide s into substrings so that each substring is a palindrome.
Returns the minimum number of split times that s meets the requirements. example, given the string s = "AaB", returns 1, because a split can divide the string s into ["AA", "B"] such two palindrome strings * * @author Dell */public class Test108 {Publi c static int mincut (String s) {if (S.equals ("") | |
S==null) return 0;
int Len=s.length ();
Boolean[][] Ishuiwen=new Boolean[len][len]; for (int l=1; l<=len;
l++) {for (int i=0;i<len-l+1;i++) {int j=i+l-1;
if (l==1) {ishuiwen[i][j]=true;
} else if (l==2) {if (S.charat (i) ==s.charat (j)) Ishuiwen[i][j]=true;
} else {if (S.charat (i) ==s.charat (j) &&ishuiwen[i+1][j-1]) ishuiwen[i][j]=true;
}}} int[] Dp=new Int[len];
for (int i=len-1;i>=0;i--) {if (ishuiwen[i][len-1]) {dp[i]=0;
Continue
} Dp[i]=integer.max_value;
for (int j=i+1;j<len;j++) {if (ishuiwen[i][j-1]&&dp[i]>dp[j]+1) {dp[i]=dp[j]+1;
} }} return dp[0];
} public static void Main (string[] args) {Scanner sc=new Scanner (system.in);
String S=sc.nextline ();
System.out.println (Mincut (s));
}
}