Palindrome PartioningII

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.

Leetcode上不用双重dp的解法:https://oj.leetcode.com/discuss/9476/solution-does-not-need-table-palindrome-right-uses-only-space 

1.双重DP

a. 首先建立一个palindrome查询表如下,表示从j到i的字符串是否为palindrome:(i-> row, j-> col)

 aab
atrue  
atruetrue 
bfalsefalsetrue
b. 第二次dp: cut[i] 表示前i-1的字符串最少的palindrome个数。 接下来扫描字符串,对于位置i,分成两段:[0, j-1] [j, i]。cut[i] = min(cut[i], cut[j]+1)

c. 注意最后返回c[s.length()]-1。因为c[i]代表了第i-1位最少的palindrome个数,cut数= 个数-1.

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

2. 和palindrome partitioningI 一样的做法,维护一个最小值,输入为ababababababababababababcbabababababababababababa超时。

public class Solution {
    int min;
    public int minCut(String s) {
        min = Integer.MAX_VALUE;
        helper(s, 0);
        return min < 0 ? 0 : min;
    }
    void helper(String s, int cut) {
        if (s.isEmpty()) {
            if (cut-1 < min) {
                min = cut-1;
            }
        }
        for (int i = 1; i <= s.length(); i++) {
            if (isPalindrome(s.substring(0, i))) {
                helper(s.substring(i), cut+1);
            }
        }
    }
    
    boolean isPalindrome (String s) {
        int n = s.length();
        for (int i = 0, j = n-1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值