【LeetCode】Palindrome Partitioning II

133 篇文章 0 订阅
121 篇文章 2 订阅

Palindrome Partitioning II 
Total Accepted: 3698 Total Submissions: 21952 My Submissions
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.
我以为应该像Palindrome Partitioning用BFS或者DFS来,发现超时。
超时的原因应该是做了很多重复的搜索,就像递归总是重复计算,迭代就会好很多。
参考各种大牛的代码,应该用DP。
int len = s.length();
声明两个数组,int []cutArr = new int[len+1];
              int [][]dp = new int[len][len];
其中cutArr[i] 表示从位置i到len-1成为回文子串的最小划分。
dp[i][j]表示子串s.substring(i,j+1)是否为回文子串。
初始化时,dp[i][i] = 1;
如果s.charAt(i) == s.charAt(j),并且dp[i+1][j-1] = 1,那么dp[i][j] = 1;
更新cutArr[i] = Math.min(cutArr[i],cutArr[j+1]+1);这句话的含义是,
从位置i到len-1的最小划分为:如果子串i到j是回文串,那么最小划分就应该更新为
(从i到j应该是一个划分,加上从j到len-1的最小划分)和(从i到len-1的划分)的最小值。
因为cutArr[i]依赖于比i大的cutArr,所以应该倒序计算。
Java AC

public class Solution {
    public int minCut(String s) {
        if(s == null || "".equals(s.trim())){
            return 0;
        }
	    int len = s.length();
	    int cutArr[] = new int[len+1];
	    int dp[][] = new int[len][len];
	    for(int i = len-1; i >= 0; i--){
	        cutArr[i] = Integer.MAX_VALUE;
	        for(int j = i; j < len; j++){
	            if(s.charAt(i) == s.charAt(j)){
	                if(j - i < 2 || dp[i+1][j-1] == 1){
	                    dp[i][j] = 1;
	                    cutArr[i] = Math.min(cutArr[i],cutArr[j+1]+1);
	                }
	            }
	        }
	    }
	    return cutArr[0]-1;
    }
}

参考http://blog.csdn.net/yutianzuijin/article/details/16850031

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值