Leikou brushing notes: 132. Split palindrome II (Dynamic programming, line-by-line code comments, mainly to make it easier to understand, other problem solutions can’t be understood at all...)

topic:

132. Split palindrome II

Give you a string s, please split s into some substrings so that each substring is a palindrome.

Returns the minimum number of splits that meet the requirements.

Example 1:

Input: s = "aab"
Output: 1
Explanation: You can split s into two palindrome substrings like ["aa","b"] only once.

Example 2:

Input: s = "a"
Output: 0

Example 3:

Input: s = "ab"
Output: 1

prompt:

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

Note: It is very similar to Question 131, but it will time out if you send it backwards. . .

Problem solution ideas:

This question is a bit complicated. New variable-length palindromes may appear when the window is sliding, so dynamic programming needs to be used to update the number of divisions. For the specific implementation method, see the code comments.

Problem solution python code:

class Solution:
    def minCut(self, s: str) -> int:
        l = len(s)
        f = [i for i in range(l)] # 前i个元素最少的分割次数
        for i in range(l):
            for j in range(i+1): # 对于第i个元素,遍历之前的所有组合进行判断
                tmp = s[j:i+1]  # 构建子串
                if tmp==tmp[::-1]: # s[j:i+1]是回文
                    if j==0: f[i] = 0  # j==0 说明[:i+1]的子串是回文串,切割线移至i+1,之前不需要再分割
                    # 更新 i 字符位置的分割次数,新的分割线为 j,即 j 之前的分割次数再加上1,则f[i]更新为f[j-1]+1
                    else: f[i] = min(f[i],f[j-1]+1) 
        return f[-1]

Author: a-qing-ge
Links: https://leetcode-cn.com/problems/palindrome-partitioning-ii/solution/dong-tai-gui-hua-xiang-xi-zhu-shi-by-aq-r5ts /
Source: LeetCode https://leetcode-cn.com/problems/palindrome-partitioning-ii/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114535591