132. Palindrome Partitioning II

来源:互联网 发布:linux mysql 存放路径 编辑:程序博客网 时间:2024/05/01 17:59

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
原创粉丝点击