【Leetcode】Palindrome Partitioning II

来源:互联网 发布:淘宝卖家版app官方下载 编辑:程序博客网 时间:2024/05/11 22:12

题目链接: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;    }
0 0
原创粉丝点击