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.

前面一道题目是要找到所有的回文子字符组合,现在是找到最小的分割数。很显然,应该用动态规划优化。

开一个数组minValue, minValue[ i ] 存储以 index i 为起点的字符串的最小分割数。

同时开一个二维数组isPal, 用来存储string中子字符串是否为回文字符。( isPal [ i ] [ j ] = isPal [ i ] [ j ] && s [ i ] == s [ j ]  )

运行时间:

代码:

public class PalindromePartitioningII {
    public int minCut(String s) {
        int[] minCache = new int[s.length()];
        boolean[][] isPal = new boolean[s.length()][s.length()];
        for (int i = s.length() - 1; i >= 0; i--) {
            for (int j = i; j < s.length(); j++) {
                if (( i + 1 > j - 1 || isPal[i + 1][j - 1]) && s.charAt(i)== s.charAt(j))
                    isPal[i][j] = true;
            }
        }

        Arrays.fill(minCache, Integer.MAX_VALUE);
        minCache[s.length() - 1] = 0;
        return doPartition(minCache, isPal, s, 0);

    }

    private int doPartition(int[] minCache, boolean[][] isPal, String s, int begin) {
        if (begin == s.length()) {
            return 0;
        }
        if (minCache[begin] != Integer.MAX_VALUE) {
            return minCache[begin];
        }
        int curMin = Integer.MAX_VALUE;
        for (int i = begin; i < s.length(); i++) {
            if (isPal[begin][i]) {
                if (i == s.length() - 1) {
                    curMin = 0;
                    break;
                }
                curMin = Math.min(curMin, doPartition(minCache, isPal, s, i + 1) + 1);
            }
        }
        minCache[begin] = curMin;
        return minCache[begin];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值