Given A string s, partition s such that every substring of the partition are 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.
Cut a few knives at least to make each part of a string a palindrome.
Ideas:
Use Cut[i] to store substrings from s[0] ~ S[i-1], and to cut a few knives in the shortest.
For convenience make cut[0] =-1
No cutter required when only one character cut[1] = 0
In other cases, assuming a cutter from ( -1 ~ i-2), if the second part of the S-cutter is a palindrome, cut[i] = cut[j] + 1; Cut[i] Take all the smallest of the tangent
The code is as follows: This is the O (N3) method, the result is timed out ....
classSolution { Public: intMincut (strings) {vector<int> Cut (s.length () +1,0); cut[0] = -1; for(inti =2; I <= s.length (); i++) { intMinnum =s.length (); for(intj =0; J < I; J + +) { if(Ispalindrome (S.substr (J, I-J )) {intnum = Cut[j] +1; Minnum=min (num, minnum); }} Cut[i]=Minnum; } returncut[s.length ()]; } BOOLIspalindrome (strings) {inti =0, j = s.length ()-1; while(I <j) {if(S[i]! = S[j])return false; I++; j--; } return true; }};
All kinds of interception can not pass, had to look at other people's thinking, the original in the judgment palindrome here to make efforts, I am every time I judge it is not a palindrome, in fact, can be previously asked to save the palindrome information, to facilitate the judgment behind.
O (N2) solution
classSolution { Public:intMincut (strings) {vector<int> Cut (s.length () +1,0); Vector<vector<BOOL>> Ispalindrome (s.length () +1, vector<BOOL> (s.length () +1,false)); cut[0] = -1; for(inti =2; I <= s.length (); i++) { intMinnum =s.length (); for(intj = i-1; J >=0; j--) { if((s[j] = = s[i-1]) && (i-1-J <2|| Ispalindrome[j +1][i-2]) {ispalindrome[j][i-1] =true; Minnum= Min (Cut[j] +1, Minnum); }} Cut[i]=Minnum; } returncut[s.length ()]; }};
There are more powerful, the above method saved the judgment palindrome information, there is a need not to save, very fast
classSolution { Public: intMincut (strings) {intn =s.size (); Vector<int> Cut (n+1,0);//Number of cuts for the first K characters for(inti =0; I <= N; i++) Cut[i] = i1; for(inti =0; I < n; i++) { for(intj =0; I-j >=0&& i+j < n && S[i-j]==s[i+j]; J + +)//Odd Length palindromecut[i+j+1] = min (cut[i+j+1],1+cut[i-J]); for(intj =1; i-j+1>=0&& i+j < n && s[i-j+1] = = S[i+j]; J + +)//even length palindromecut[i+j+1] = min (cut[i+j+1],1+cut[i-j+1]); } returnCut[n]; }};
"Leetcode" palindrome partitioning II (hard) ☆