Divide it into some substrings into palindrome strings, and return the minimum number of divisions that meet the requirements.

Link: 132. Split Palindrome String II - LeetCode

Given a string  s, please split it  s into substrings so that each substring is a palindrome.

Returns  the minimum number of divisions that meet the requirements  .

Example 1:

Input: s = "aab"
 Output: 1
 Explanation: It only takes one split to  split s into two palindrome substrings ["aa", "b"].

Example 2:

Input: s = "a"
 Output: 0

Example 3:

Input: s = "ab"
 Output: 1

hint:

  • 1 <= s.length <= 2000
  • s Consists of only lowercase English letters

Idea:

Define dp[i] as the minimum number of splits required to split all s[0...i] into strings

Define isRound[i][j] to indicate whether the string s[j...i] is a string

State transition equation:

        The first thing to make clear is that i walks from left to right and j walks from right to left;

        When s[i] == s[j] and the substring (s[i+1,i-1] is a palindrome string, that is, isRound[i][j] = True or s[i..j] only one or two characters):

                dp[i] = min(dp[i],dp[j-1]+1)

        Why is dp[j-1]+1? This is to treat the string after j as a whole divisible palindrome string, and then cut it at j

One thing to note is that when it is successfully determined that the current string is a palindrome string, if j equals 0, it means that the entire character is a string, just set dp[i] = 0

class Solution:
    def minCut(self, s: str) -> int:
        n = len(s)

        dp = [0 for i in range(n+1)]
        isRound = [[False for i in range(n+1)] for j in range(n+1)]

        for i in range(1,n):
            dp[i] = i
            for j in range(i,-1,-1):
                if s[i] == s[j] and (isRound[j+1][i-1] or i-j<2):
                    isRound[j][i] = True
                    if j==0: dp[i] = 0
                    else : dp[i] = min(dp[i],dp[j-1]+1)

        return dp[n-1]

             

Guess you like

Origin blog.csdn.net/qq_51118755/article/details/133379596
Recommended