132. Palindrome Partitioning II

来源:互联网 发布:golang vendor 编辑:程序博客网 时间:2024/05/23 00:10

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.


The idea is to maintain a result from i = 0  to (i - 1)

when the ith letter comes in dp[i] = min(dp[j - 1] + 1) for all the j that s(j -> i) is a palindrome .

Code:

public class Solution {    public int minCut(String s) {        int[] dp = new int[s.length() + 1];        for(int i = 1; i < dp.length; i++){            dp[i] = Integer.MAX_VALUE;            for(int j = i; j > 0; j--){                if(isPanlindrome(s,j - 1,i - 1)){                    dp[i] = Math.min(dp[i],1 + dp[j - 1]);                }            }        }        return dp[dp.length - 1] - 1;                    }        public boolean isPanlindrome(String s, int start, int end){        while(start < end){            if(s.charAt(start) == s.charAt(end)){                start++;                end--;            } else {                return false;            }        }        return true;    }}

Time complexity O(N3). since
isPanlindrome() takes O(n)


This code will get TLE on Leetcode since for isPanlindrome part, there are many redundant computation. 

For example "baaab" we already know that in the first "baaa" the aaa is a panlidrome. when the last b comes in , we should only check "b***b" and the info about "aaa" should be stored to improve the performance.

if s(i) != s(j)     p[i][j] = false;

else p[i][j] = p[i - 1][j + 1].

code:

public class Solution {    public int minCut(String s) {        int[] dp = new int[s.length() + 1];        boolean[][] p = new boolean[s.length()][s.length()];        for(int i = 0 ; i < s.length(); i++){            p[i][i] = true;        }        for(int i = 0 ; i < s.length() - 1; i++){            p[i][i+1] = (s.charAt(i) == s.charAt(i+1));        }                for(int l = 2; l < s.length(); l++){            for(int i = 0 ; i < s.length() - l; i++){                int j = i + l;                if(s.charAt(i) == s.charAt(j)){                    p[i][j] = p[i + 1][j - 1];                }            }        }                        for(int i = 1; i < dp.length; i++){            dp[i] = Integer.MAX_VALUE;            for(int j = i; j > 0; j--){                if(p[j - 1][i - 1]){                    dp[i] = Math.min(dp[i],1 + dp[j - 1]);                }            }        }        return dp[dp.length - 1] - 1;                    }}


The pre-process of the data is important to avoid TLE, total Time O(n2).





0 0