首页 > 编程语言 > 详细

Java for LeetCode 132 Palindrome Partitioning II

时间:2015-06-01 22:02:05      阅读:184      评论:0      收藏:0      [点我收藏+]

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];
    }

 


                   

Java for LeetCode 132 Palindrome Partitioning II

原文:http://www.cnblogs.com/tonyluis/p/4544882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!