码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Palindrome Partitioning II

时间:2016-06-11 10:39:50      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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.

思路:
dp
c[i]表示从下标0~i的字符串 最少由几个回文串组合而成
dp[i][j]表示下标j~i的字符串是否是回文串

状态转移方程:
0<=j<=i
if j~i是回文串
c[i]=min{c[j-1]+1,c[i]}
这里判断j~i是否是回文串不能暴力判断了否则会超时,需要利用之前判断过的结果。即若charAt[j]==charAt[i] &&dp[j+1][i-1],则dp[j][i]也是回文串。
这里要注意边界情况,即当j=i或j+1==i时,若charAt[j]==charAt[i],则j~i也是回文串,防止出现对j+1>i-1的判断。
时间复杂度O(n^2),空间复杂度O(n^2)。

算法:

    public int minCut(String s) {
        if (s.length() == 0)
            return 0;

        int c[] = new int[s.length()];// 0~i的字符串最少是几个回文串的组合
        boolean dp[][] = new boolean[s.length()][s.length()];// 从i~j字符串是否是回文

        for (int i = 0; i < s.length(); i++) {
            dp[i][i] = true;
            c[i] = i + 1;
            for (int j = 0; j <= i; j++) {
                if (s.charAt(j) == s.charAt(i) && (j == i || j + 1 == i || dp[j + 1][i - 1])) {
                    dp[j][i] = true;
                    if (j > 0) {
                        c[i] = Math.min(c[i], c[j - 1] + 1);
                    } else {
                        c[i] = Math.min(c[i], 1);
                    }
                }
            }
        }
        return c[s.length() - 1] - 1;
    }

【Leetcode】Palindrome Partitioning II

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51635561

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!