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

这道题开始的时候用了backtracking去解,结果超时了……也难怪,回溯的时间复杂度是O(n^n),跟DP的O(n^2)比简直慢到爆炸……

只说DP解法好了。

1、建立cut[n]来保存每一个字符处能切次数的最小值,如果s[j, i]是回文,那么cut[i] = cut[j - 1]+1

2、建立isPalindrome[n][n]数组保存s[j, i]是不是回文,如果s[j, i]是回文,那么肯定s[j] == s[i],而且isPalindrome[j+1][i-1]==true,这时候就需要更新cut[i] = cut[j-1]

代码如下:

public class Solution {
    public int minCut(String s) {
        int len = s.length();
        int[] cut = new int[len];
        boolean[][] isPalindrome = new boolean[len][len];
        char[] cs = s.toCharArray();
        for (int i = 0; i < len; i ++) {
            int min = i;
            for (int j = 0; j <= i; j ++) {
                if (cs[i] == cs[j] && (j + 1 > i -1 || isPalindrome[j + 1][i - 1])) {
                    isPalindrome[j][i] = true;
                    min = Math.min(min, j == 0? 0: cut[j - 1] + 1);
                }
            }
            cut[i] = min;
        }
        return cut[len - 1];
    }
}
另一种O(n)space的方法,不需要isPalindrome[n][n]数组,是遍历s[n],每次的s[i]向外发散,分为奇数序列和偶数序列两种情况,然后动态更新cut[i]也很巧妙,代码如下:

public class Solution {
    public int minCut(String s) {
        int n = s.length();
        char cs[] = s.toCharArray();
        int[] cut = new int[n + 1];  // number of cuts for the first k characters
        for (int i = 0; i <= n; i++) cut[i] = i-1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; i-j >= 0 && i+j < n && cs[i-j]==cs[i+j] ; j++) // odd length palindrome
                cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j]);

            for (int j = 1; i-j+1 >= 0 && i+j < n && cs[i-j+1] == cs[i+j]; j++) // even length palindrome
                cut[i+j+1] = Math.min(cut[i+j+1],1+cut[i-j+1]);
        }
        return cut[n];
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值