Leetcode: palindrome partitioning II [0, 132]

Source: Internet
Author: User
[Question]

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",
Return1Since the palindrome partitioning["aa","b"]Cocould be produced using 1 cut.


Question]

Given a string S, the minimum number of splits is returned. Yes, all the substrings are input.


[Idea]

DP, and determine the minimum number of Split times of S [1... n] in sequence
Assume that mincuts [I] is used to represent the minimum number of times the string ending with I is split.
So how to determine mincuts [I]. We know mincuts [J] J =,..., I-1
For each position J before I, if s [J + 1,..., I] is the input string, the minimum number of times J is cut at the cutting point is mincuts [J] + 1;
Therefore, we need to take a position from all J so that the position with the smallest number of cut times at the I position is used as the cutting point, mincuts [I] = min {mincuts [J] + 1} s [J + 1 ,.., i] is input, j = 0, 1... i-1


[Code]
Class solution {public: int mincut (string s) {int Len = S. length (); If (LEN = 0 | Len = 1) return 0; // construct the echo discriminant matrix vector <bool> ispal (Len, vector <bool> (Len, false); // initialize ispal [I] [I] for (INT I = 0; I <Len; I ++) ispal [I] [I] = true; // initialize ispal [I] [I + 1] For (INT I = 0; I <len-1; I ++) if (s [I] = s [I + 1]) ispal [I] [I + 1] = true; // initialize other I <j substrings for (INT I = len-3; I> = 0; I --) for (Int J = I + 2; j <Len; j ++) ispal [I] [J] = (s [I] = s [J]) & Ispal [I + 1] [J-1]; // returns the smallest cut vector <int> mincuts (Len, 0 ); // record the minimum cut score of the substring ending with I for (INT I = 0; I <Len; I ++) {int mincut = int_max; for (Int J =-1; j <I; j ++) {If (ispal [J + 1] [I]) {If (j =-1) mincut = 0; else if (mincuts [J] + 1 <mincut) mincut = mincuts [J] + 1 ;}} if (mincut! = Int_max) mincuts [I] = mincut;} return mincuts [len-1];};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.