Palindrome Partitioning II
Given a string s, partition s such thatevery substring of the partition is a palindrome.
Return the minimum cuts needed for apalindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning["aa","b"] could be produced using 1 cut.
最小回文切割数:
输入一个字符串s,用最小的切割次数把s切割成子串都是回文,求这个最小的切割次数。
这里就简单说说思想好了:
这题为了不贪心,我用了递归搜索,把字符串s(长度为l)由头往后扫:
1. 如果出现前面x位为回文,就用1加上后面(l-x)位的的最小切割次数;
2. 把上述情况所有可能中的最小值记下来作为s的最小切割次数返回。
具体Java代码如下:
import java.util.Scanner;
public class huiwen {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String s=sc.next();
System.out.println(think(s));
}
private static int think(String s) {
// TODO Auto-generated method stub
String x;
int i,j=0;
if(huiwen((String) s.subSequence(0,s.length()))==true)return 0;
for(i=1;i<s.length();i++)
{
if(huiwen((String) s.subSequence(0,i))==true)
{
if(j==0)j=1+think((String) s.subSequence(i,s.length()));
else j=min(j,1+think((String) s.subSequence(i,s.length())));
}
}
return j;
}
//取最小值函数
private static int min(int i, int j) {
// TODO Auto-generated method stub
if(i>j)return j;
else return i;
}
//判断是否回文函数
private static boolean huiwen(String s) {
// TODO Auto-generated method stub
int n=s.length();
if(n==1||n==0)return true;
else
{
if(s.charAt(0)==s.charAt(n-1))return huiwen((String) s.subSequence(1,s.length()-1));
else return false;
}
}
}