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