"Leetcode" Palindrome partitioning II

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/palindrome-partitioning-ii/

Topic:
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.

Ideas:
Dp
C[i] means that a string from subscript 0~i is composed of at least a few palindrome strings.
DP[I][J] Indicates whether a string of subscript j~i is a palindrome

State transition equation:
0<=j<=i
If J~i is a palindrome string
C[i]=min{c[j-1]+1,c[i]}
Here to determine whether J~i is a palindrome can not be violent judgment or will time out, need to use the results previously judged. Even if Charat[j]==charat[i] &&dp[j+1][i-1], then Dp[j][i] is also a palindrome string.
Here to pay attention to the boundary situation, that is, when j=i or j+1==i, if charat[j]==charat[i], then J~i is also palindrome string, to prevent the appearance of the J+1>i-1 judgment.
Time complexity O (n^2), Spatial complexity O (n^2).

Algorithm:

PublicintMincut (String s) {if(S.length() ==0)return 0;intC[] = newint[S.length()];//0~i string minimum is a combination of several palindrome stringsBoolean dp[][] = new Boolean[s.length()][s.length()];//Whether the string from I~j is a palindrome         for(inti =0; I < S.length(); i++) {Dp[i][i] =true; C[i] = i +1; for(intj =0; J <= I; J + +) {if(S.charat (j) = = S.charat (i) && (j = = I | | J +1= = I | | Dp[j +1][i-1]) {Dp[j][i] =true;if(J >0) {C[i] = Math.min(C[i], c[j-1] +1); }Else{C[i] = Math.min(C[i],1); }                }            }        }returnC[s.length() -1] -1; }

"Leetcode" Palindrome partitioning II

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.