LeetCode 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.



一般DP,超时了,因为没有将判断回文字的部分优化。


import java.awt.Image;


public class Solution {
	
	
	boolean isPalindrome(String s, int u,int v){
		
		int head = u;
		int tail = v;
		while(head<tail){
			if(s.charAt(head)!=s.charAt(tail)){
				return false;
			}
			head++;
			tail--;
		}
		return true;
	}
    public int minCut(String s) {
        
    	
    	if(s==null)return 0;
    	
    	if(isPalindrome(s, 0, s.length()-1)){
    		
    		System.out.println(0);
    		
    		return 0;
    	}
    	
    	
    	int n = s.length();
		boolean[][] PalindromePair = new boolean [n][n];
		
		for(int i=0;i<n;i++){
			for(int j=i+1;j<n;j++){
				PalindromePair[i][j]=isPalindrome(s, i, j); 
			}
		}
		
		int [] []DpCount = new int [n][n];
		
		for(int i=0;i<n;i++){
			
			DpCount[i][i]=0;
			for(int j=i+1;j<n;j++){
				
				if(PalindromePair[i][j]){
					DpCount[i][j]=0;
				}
				else{
					DpCount[i][j]=j-i;
				}
			}
		}
		
		for(int k=1;k<n;k++){
			
			for(int i=0;i<n-k;i++){
				
				for(int j=i+1;j<k+i;j++){
					
					DpCount[i][i+k]=Math.min(DpCount[i][i+k], DpCount[i][j]+DpCount[j+1][i+k]+1);
				}
			}
		}
		return DpCount[0][n-1];
    }
    
    public static void main(String[]args){
    	
    	Solution solution = new Solution();
    	
    	String string = new String("aab");
    	
    	System.out.println(solution.minCut(string));
    }
}




下面的算法实际上是两个动态规划算法的结合,一个是 动态规划求回文字,一个是动态规划求前i个字符有多少个回文字。

DPCount[i]表示子串[0,i]最少切割多少次






public class Solution {
	
	

    public int minCut(String s) {
        
    	
    	if(s==null)return 0;
    	
    	int n = s.length();
    	
    	if(n<2)return 0;
    	
		boolean[][] PalindromePair = new boolean [n][n];
		
		int [] DPCount = new int [n];
		
		for(int i=0;i<n;i++){
			DPCount[i]=i;
		}
		for(int i=0;i<n;i++){
			
			
			if(s.charAt(0)==s.charAt(i)&&((i<2)||PalindromePair[1][i-1])){
				PalindromePair[0][i]=true;
				DPCount[i]=0;
			}
			
			for(int j=1;j<=i;j++){
				
				if(s.charAt(j)==s.charAt(i)&&((i-j<2)||PalindromePair[j+1][i-1])){
					
					PalindromePair[j][i]=true;
					
					DPCount[i]=Math.min(DPCount[i], DPCount[j-1]+1);
				}
				
			}
		}
		
		return DPCount[n-1];
    }
    
    public static void main(String[]args){
    	
    	Solution solution = new Solution();
    	
    	String string = new String("aab");
    	
    	System.out.println(solution.minCut(string));
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值