[leetcode]Palindrome Partitioning II

本文详细解析了回文分割最小切割数问题的解决方法,通过动态规划实现优化,避免了逐个检查子串是否为回文的冗余步骤。通过构建二维数组标记回文串,并利用状态转移方程简化计算过程,最终得到最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新博文地址:

 

[leetcode]Palindrome Partitioning II

 

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,但是状态转移方程实在是想不出来。。。。所以看了一下别人的算法,是厉害。

具体算法:

1.  确定字符串s的最小切割数

2. 则字符串 ‘#’ + s 的最小切割数则是遍历s,如果遇到‘#’(假设#在s中的索引是i)则'#' + s的切割数即为s.substring(1) 的切割数或者+ 1(如果#出现在s的最后一个位置,则不需要+1)

因此状态转移方程为 result[i] = min(result[i] , result[j + 1] + 1) (当j + 1 != length时)result[i] = min(result[i] , result[j + 1] )(当j + 1 == length时)

这个算法很腻害的是,没有计算某个字符子串是否是回文的,而是用一个二维数组来标记是否是回文,很值得借鉴。

不罗嗦了,代码如下:不明白可以吐槽

 

  public int minCut(String s) {
    	if( s == null || s.length() < 2){
    		return 0;
    	}
    	int[] result = new int[s.length() + 1];
    	boolean[][] map = new boolean[s.length()][s.length()];
    	for(int i = s.length() - 1; i >=0 ; i--){
    		result[i] = s.length() - i - 1;
    		for(int j = i ; j < s.length(); j++){
    			if(s.charAt(i) == s.charAt(j)){
    				if(j - i <= 1 || map[i + 1][j - 1] == true){
    					map[i][j] = true;
    					if(j == s.length() - 1){
    						result[i] = Math.min(result[i], result[j + 1]);
    					}
						result[i] = Math.min(result[i], result[j + 1] + 1);
    				}
    			}
    		}
    	}
    	return result[0];
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值