Java for LeetCode 132 Palindrome Partitioning II

本文探讨了如何使用动态规划解决回文分区问题,详细解释了算法思路,并提供了Java实现代码。

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.

解题思路:

因为是Hard,用上题的结果计算肯定是超时的,本题需要用dp的思路,开一个boolean[][]的数组计算i-j是否为palindrome,递推关系为s.charAt(j) == s.charAt(i) &&  isPal[j + 1][i - 1]) → isPal[j][i] = true,同时dp[i] = Math.min(dp[i], dp[j - 1] + 1),JAVA实现如下:

    public int minCut(String s) {
		int[] dp = new int[s.length()];
		for (int i = 0; i < dp.length; i++)
			dp[i] = i;
		boolean isPal[][] = new boolean[s.length()][s.length()];
		for (int i = 1; i < s.length(); i++)
			for (int j = i; j >= 0; j--) 
				if (s.charAt(j) == s.charAt(i)
						&& (j + 1 >= i - 1 || isPal[j + 1][i - 1])) {
					isPal[j][i] = true;
					dp[i] = j == 0 ? 0 : Math.min(dp[i], dp[j - 1] + 1);
				}
		return dp[dp.length - 1];
    }

 


                   

转载于:https://www.cnblogs.com/tonyluis/p/4544882.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值