LeetCode 132 - Palindrome Partitioning II


Related: Leetcode 131 - Palindrome Partitioning
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.
X. O(n) space - expand

public int minCut(String s) { if(s==null || s.length()<2){ return 0; } int n = s.length(); char[] t = s.toCharArray(); int[] dp = new int[n+1]; Arrays.fill(dp,Integer.MAX_VALUE); dp[0] = -1; int i = 0; while(i<n){ expand(t,dp,i,i); expand(t,dp,i,i+1); i++; } return dp[n]; } private void expand(char[] t,int[] dp,int i,int j){ while(i>=0 && j<t.length && t[i] == t[j]){ dp[j+1] = Math.min(dp[j+1],dp[i] + 1); i--;j++; } }

public int minCut(String s) { int len = s.length(); int[] f = new int[len]; for (int i = 0; i < len; i++) { f[i] = i; } for (int i = 0; i < len; i++) { search(s, f, i, i); search(s, f, i, i + 1); } // System.out.println(Arrays.toString(f)); return f[len - 1]; } private void search(String s, int[] f, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { if (left == 0) { // left == 0, substring(0, right+1) is palindrom, no cut needed f[right] = 0; } else { f[right] = Math.min(f[right], f[left - 1] + 1); } left--; right++; } }

https://discuss.leetcode.com/topic/2840/my-solution-does-not-need-a-table-for-palindrome-is-it-right-it-uses-only-o-n-space/12
  public int minCut(String s) {
        if(s.length()==0)return 0;
        int[]c=new int[s.length()+1];
        for(int i=0;i<s.length();i++)c[i]=Integer.MAX_VALUE;
        c[s.length()]=-1;
        for(int i=s.length()-1;i>=0;i--){
            for(int a=i,b=i;a>=0 && b<s.length() && s.charAt(a)==s.charAt(b);a--,b++) c[a]=Math.min(c[a],1+c[b+1]);
            for(int a=i,b=i+1;a>=0 && b<s.length() && s.charAt(a)==s.charAt(b);a--,b++) c[a]=Math.min(c[a],1+c[b+1]);
        }
        return c[0];
    }
https://github.com/liguangsheng/leetcode/blob/master/132-Palindrome-Partitioning-II.MD
使用一个数组cut来记录回文串的分组,一个字符串最多可以分为每个字符一组,也就是n组(n为字符串长度)。初始化cut为1...n。
遍历每个字符作为中心,然后偏移量offset逐渐增加,判断中心两侧offset的字符是否相等,来判断是否回文。
这里注意回文有两种,一种形如"abcba"的奇数串,一种形如"abba"的偶数串,要分别处理。
当某个字符作为中心时,当前回文串的低位的前一位记录的是前一组的组别,+1之后得到当前回文串的组别,用+1之后的值和其本身的值比较,然后将较小值写入高位,使高位记录当前回文串的组别。
动态更新cut数组,最终可推导出最后一个分组,最后一个分组的组别号-1就是分割次数。
int minCut(char *s) {
    int len = strlen(s);
    int cut[len + 1];
    for(int i = 0; i <= len; i++) cut[i] = i;
    for(int center = 0; center < len; center++) {
        for(int offset = 0; center - offset >= 0 && center + offset < len
              && s[center - offset] == s[center + offset]; offset++)
            cut[center + offset + 1] = MIN(cut[center + offset + 1], cut[center - offset] + 1);
        for(int offset = 0; center - offset - 1 >= 0 && center + offset < len
              && s[center - offset - 1] == s[center + offset]; offset++)
            cut[center + offset + 1] = MIN(cut[center + offset + 1], cut[center - offset - 1] + 1);
    }
    return cut[len] - 1;
}

X. DP - Compute isPalindrom[][] and cuts[] at same time
http://www.cnblogs.com/grandyang/p/4271456.html
这道题是让找到把原字符串拆分成回文串的最小切割数,需要用动态规划Dynamic Programming来做,使用DP的核心是在于找出递推公式,之前有道地牢游戏Dungeon Game的题也是需要用DP来做,而那道题是二维DP来解,这道题由于只是拆分一个字符串,需要一个一维的递推公式,我们还是从后往前推,递推公式为:dp[i] = min(dp[i], 1+dp[j+1] )    i<=j <n,那么还有个问题,是否对于i到j之间的子字符串s[i][j]每次都判断一下是否是回文串,其实这个也可以用DP来简化,其DP递推公式为P[i][j] = s[i] == s[j] && P[i+1][j-1],其中P[i][j] = true if [i,j]为回文
http://happycoding2010.blogspot.com/2015/10/leetcode-132-palindrome-partitioning-ii.html
https://discuss.leetcode.com/topic/32575/easiest-java-dp-solution-97-36
Use DP. dp[i][j] store if s[i..j] is palindrome or not. res[j] is the min cut of s[0..j]. In the loop, keep update dp[i][j] matrix and res[j] array. The complexity is O(N^2).
   public int minCut(String s) {  
     int n=s.length();  
     char[] c=s.toCharArray();  
     boolean[][] dp=new boolean[n][n];  
     int[] res=new int[n];  
     for (int j=0; j<n; j++) {  
       res[j]=Integer.MAX_VALUE;  
       for (int i=j; i>=0; i--) {  
         dp[i][j]=i==j || (c[i]==c[j] && (i+1>=j-1 || dp[i+1][j-1]));  
         if (dp[i][j]) {  
           int cut=(i==0)?0:res[i-1]+1;  
           res[j]=Math.min(res[j],cut);  
         }  
       }  
     }  
     return res[n-1];  
   }  
public int minCut(String s) {
    int n = s.length();
 
 boolean dp[][] = new boolean[n][n];
 int cut[] = new int[n];
 
 for (int j = 0; j < n; j++) {
  cut[j] = j; //set maximum # of cut
  for (int i = 0; i <= j; i++) {
   if (s.charAt(i) == s.charAt(j) && (j - i <= 1 || dp[i+1][j-1])) {
    dp[i][j] = true;
 
    // if need to cut, add 1 to the previous cut[i-1]
    if (i > 0){
     cut[j] = Math.min(cut[j], cut[i-1] + 1);
    }else{
    // if [0...j] is palindrome, no need to cut    
     cut[j] = 0; 
    } 
   }
  }
 }
 
 return cut[n-1];
}

  1. pal[i][j] , which is whether s[i..j] forms a pal
  2. d[i], which is the minCut for s[i..n-1]
Once we comes to a pal[i][j]==true:
  • if j==n-1, the string s[i..n-1] is a Pal, minCut is 0, d[i]=0;
  • else: the current cut num (first cut s[i..j] and then cut the rest s[j+1...n-1]) is 1+d[j+1], compare it to the exisiting minCut num d[i], repalce if smaller.
d[0] is the answer.
int minCut(string s) { if(s.empty()) return 0; int n = s.size(); vector<vector<bool>> pal(n,vector<bool>(n,false)); vector<int> d(n); for(int i=n-1;i>=0;i--) { d[i]=n-i-1; for(int j=i;j<n;j++) { if(s[i]==s[j] && (j-i<2 || pal[i+1][j-1])) { pal[i][j]=true; if(j==n-1) d[i]=0; else if(d[j+1]+1<d[i]) d[i]=d[j+1]+1; } } } return d[0]; }
X. DP - Compute isPalindrom[][] then cuts[]
    public int minCut(String s) 
    {
        if(s == null || s.isEmpty())  
            return 0;
        // Building a dict
        boolean[][] dict = buildDict(s);
         
        // result[i] means from s[0,i], the min cut
        int[] result = new int[s.length() + 1];
        result[0] = 0;
        for (int i = 0 ; i < s.length() ; i ++)
        {
            result[i + 1] = i + 1// max cut: single char cut
            for (int j = 0 ; j <= i ; j ++)
            {
                if (dict[j][i])
                {
                    result[i + 1] = Math.min(result[i + 1], result[j] + 1);
                }
            }
        }
         
        return result[result.length - 1] - 1;
    }
     
    // dict[i][j] means substring(i, j + 1) is palin
    // dict(i, j) = char[i] == char[j] && dict(i + 1, j - 1)
    // So i starts from s.length to 0
    // j starts from i to s.length
    private boolean[][] buildDict(String s)
    {
        int len = s.length();
        boolean[][] dict = new boolean[len][len];
         
        for (int i = len - 1 ; i >= 0 ; i --)
        {
            for (int j = i ; j < len ; j ++)
            {
                if (i == j)
                    dict[i][j] = true;
                else if(i + 1 == j)
                    dict[i][j] = s.charAt(i) == s.charAt(j);
                else
                    dict[i][j] = s.charAt(i) == s.charAt(j) && dict[i + 1][j - 1];
            }
        }
        return dict;
    }
http://bangbingsyb.blogspot.com/2014/11/leetcode-palindrome-partitioning-i-ii.html
http://yucoding.blogspot.com/2013/08/leetcode-question-133-palindrome.html

X.https://leetcode.com/discuss/31828/my-accepted-java-solution
So my thought process was go through the string, char by char starting from the left. The current character would be the center of the palindrome and expand as much as I can. After it ceases to be a palindrome (e.g no longer matching end chars or reached the boundary of the string), the cost would be "1 + the cost of the substring I already processed to the left of the current palindrome I am on". I compare this cost under the index of the last char of my current palindrome. If it is less than what was previously recorded, the I record this new cost.
For example, let's take 'abb':
  • Start with 'a'. Obviously a cost of 0 (base case)
  • Now we go to 'b' (index 1). Since we haven't visited 'b', let's assign an initial cost to it, which is 1 + cost[0]. So cost[1] = 0+1 = 1. This makes sense since you only need a 1 cut to get two palindromes: 'a' and 'b'
  • Let's try to expand 'b'
    • 'ab': It's not a palindrome so do nothing
    • 'abb': Not a palindrome either
  • After expansion, cost[1] remains 1.
  • Now we go to 'b' (index 2). Initial cost[2] = cost[1]+1 = 2. Expanding...
    • 'bb': Hey, a palindrome! So I will compute a cost of cost[0]+1 = 1 (remember "1 + cost of substring to the left...). Is 1 less than what I initially have in cost[2]? Yup, it is. So I record it: cost[2] = 1
  • After expansion, cost[2] was changed from 2 to 1, and rightfully so because that is the minimum cut we can do to get all substrings as palindromes: 'a' and 'bb'.
Another example but we'll go faster this time: 'xccx'
  • 'x': cost[0] = 0. Base case.
  • 'c' (index 1): Init cost[1] = 1. Expanding...
    • 'xc': Nope
    • 'xcc': Nope
  • 'c': Init cost[2] = 2. Expanding...
    • 'cc->xccx': Yes. Since we reached start of string, this is a base case. So new cost = 0. Is 0 > cost[3] = Integer.MAX_VALUE? Yes, so cost[3] = 0
    • 'ccx': Nope
  • 'x': Since cost[3] was previously entered a cost, we don't need to init. Expanding...
    • 'cx': Nope
  • Cost to cut entire string: cost[3] = 0
So there you go. With this method, you are assured that remaining substring (or 'previous state') to the left of the current palindrome is the minimum at that point because you already computed it earlier. You just need to +1 to the cost and see if you have a new minimum cost for the state you are currently in (the last character of the current palindrome).
int[] cost; public int minCut(String s) { if (s == null || s.length() < 2) return 0; int N = s.length(); cost = new int[N]; for (int i = 0; i < N; i++) cost[i] = Integer.MAX_VALUE; cut(s); return cost[N-1]; } private void cut (String s) { if (s.length() > 0) cost[0] = 0; if (s.length() > 1) cost[1] = s.charAt(1) == s.charAt(0) ? 0 : 1; int k = 0, l = 0, ni = 0; for (int i = 2; i < s.length(); i++) { if (cost[i] == Integer.MAX_VALUE) cost[i] = cost[i-1]+1; for (int j = 1; j <= 2; j++) { for (k = i-j, l = i; k >= 0 && l <= s.length()-1 && s.charAt(k) == s.charAt(l); k--, l++) { int c = k == 0 ? 0 : cost[k-1]+1; if (cost[l] > c) cost[l] = c; } } } }

For Palindrome related problems, - DP and isPalindrome[][].

https://discuss.leetcode.com/topic/6414/dp-solution-some-thoughts
  1. return the mininum cut of the partition s => optimization => DP
  2. try to divide & conqure =>
public int minCutRecur(String s){
int n = s.length;
    //base case
    if(s < 2 || isPalindr(s)) return 0;
    int min = n - 1;
    for(int i = 1; i <= n - 1; i++){
        if(isPalindr(s)){
            min = Math.min(min, 1 + minCutRecur(s.substring(i)));
        }
    }
    
    return min;
}
However, sub problem overlapped (are not independent with each other).
  1. Use DP to build the solution from bottom up.
    public int minCut(String s) {
    int n = s.length();
         boolean[][] isPalindr = new boolean[n + 1][n + 1]; //isPalindr[i][j] = true means s[i:j) is a valid palindrome
         int[] dp = new int[n + 1]; //dp[i] means the minCut for s[0:i) to be partitioned 
    
         for(int i = 0; i <= n; i++) dp[i] = i - 1;//initialize the value for each dp state.
         
         for(int i = 2; i <= n; i++){
             for(int j = i - 1; j >= 0; j--){
                 //if(isPalindr[j][i]){
                 if(s.charAt(i - 1) == s.charAt(j) && (i - 1 - j < 2 || isPalindr[j + 1][i - 1])){
                     isPalindr[j][i] = true;
                     dp[i] = Math.min(dp[i], dp[j] + 1);
                 }
             }
         }
         
         return dp[n];
    
    }
Several optimizations include:
  1. No need to check if a string is a palindrome or not inside the loop by adjusting the order of getting of solution of the sub problems.
  2. assign dp[0] to be -1 so that when s[0:i) is a palindrome by itself, dp[i] is 0. This is for the consistency of the code.
The time complexity and the space complexity are both O(n ^ 2).

http://www.jiuzhang.com/solutions/palindrome-partitioning-ii/
https://segmentfault.com/a/1190000007660424
用cuts[i]表示当前位置最少需要切几次使每个部分都是回文。如果s(j,i)这部分是回文,就有cuts[i] = cuts[j-1] + 1。
现在我们需要做的就是对于已经搜索并确定的回文部分,用一个二维数组来表示。matrix[j] [i]表示j到i这部分是回文。
如果s.charAt(i) == s.charAt(j) && isPalindrome[j+1] [i-1]是回文,则不需重复该部分的搜索。isPalindrome[j] [i]也是回文。
以"abcccba"为例:
i不断向后扫描, j从头开始知道i(包含i).
i=3即第二个c那里,j走到2, c[i] == c[j] == 'c' && i - j = 1 < 2, 填表,求最值。
i=4即第三个c那里,j走到2, c[i] == c[j] == 'c' && isPalindrome(2+1,4-1), 填表,求最值。
i=5即第二个b那里,j走到1, c[i] == c[j] == 'b' && isPalindrome(1+1,5-1)即“ccc“, 填表,求最值。
使用isPalindrome的好处就是可以O(1)的时间,也就是判断头尾就可以确定回文。不需要依次检查中间部分。
X. https://blog.csdn.net/magicbean2/article/details/71158084
1、朴素动态规划法(无法通过大数据):
    int minCut(string s) {
        int length = s.length();
        if (length == 0) {
            return 0;
        }
        vector<vector<int>> dp(length, vector<int>(length, INT_MAX));
        for (int i = 0; i < length; ++i) {
            dp[i][i] = 0;
        }
        for (int len = 2; len <= length; ++len) {
            for (int start = 0; start + len <= length; ++start) {
                int end = start + len - 1;
                if (isPalindrome(s, start, end)) {
                    dp[start][end] = 0;
                }
                else {
                    for (int k = start; k < end; ++k) {
                        dp[start][end] = min(dp[start][end], dp[start][k] + dp[k + 1][end] + 1);
                    }
                }
            }
        }
        return dp[0][length - 1];
    }
private:
    bool isPalindrome(string& s, int left, int right) { 
        int i = left, j = right; 
        while(i < j) { 
            if(s[i] != s[j]) 
                return false; 
            ++i, --j; 
        } 
        return true; 
    }


Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts