Leetcode palindrome Partitioning II

Source: Internet
Author: User

Palindrome Partitioning II of leetcode problem solving

Splitting a string into substrings makes the substring a palindrome string, requiring a minimum of several splits to meet the requirements.

Note the point:

    • No

Example:

Input: s = "AaB"

Output: 1 (Divided into "AA" and "B")

Thinking of solving problems

It can be resolved by dynamic planning, Dp[i] represents the minimum number of cuts required by the string s[:i+1], and the initial value of Dp[i] is I, because a string of i+1 length can be cut to meet the requirements of the topic. When a character is added, we need to determine in turn whether the substring at the end of it is a palindrome string, and if so, the minimum number of cuts required to calculate the remaining string plus whether the current minimum number of cuts will be minimized, note that if the entire string is a palindrome string at this point, the minimum cut count is 0. The recursive expression is as follows:

0, 如果s[:i+1]是回文串dp[i] = min(dp[i], dp[j-1]+1), 如果s[j:i+1]是回文串

In order to reduce the evaluation of palindrome strings, we use a two-dimensional array isPal[j][i] to cache the judgment result, isPal[j][i] indicating whether the string s[j:i+1] is a palindrome string.

AC Source
 class solution(object):     def mincut(self, s):        "" " : Type S:str:rtype:list[list[str]] " ""n = Len (s) dp = [0  for__inchRange (n)] Ispal = [[False  for__inchRange (n)] for__inchRange (n)] forIinchRange (n): M = i forJinchRange (i +1):ifS[J] = = S[i] and(j +1> I-1 orIspal[j +1][i-1]): ispal[j][i] =Truem =0 ifj = =0 ElseMin (M, Dp[j-1] +1) Dp[i] = mreturndp[-1]if__name__ = ="__main__":assertSolution (). Mincut ("AaB") ==1

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

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.