zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):132-Palindrome Partitioning II

    题目来源:

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


    题意分析:

      给定一个s,可以将s拆成若干个回文子字符串之和,如果拆成了m个子字符串,那么我们称s可以被m-1 cut。那么返回s的最小cut。


    题目思路:

      这是一个动态规划问题。这里需要二重动态规划,一个用来记录p[i][j]判断s[i][j]是否回文字符串,另外一个ans[i]代表s[:i]的最小cut是多少。如果s[i :j]是回文字符串,那么ans[j] = min(ans[j],ans[i - 1] + 1)。


    代码(python):

     1 class Solution(object):
     2     def minCut(self, s):
     3         """
     4         :type s: str
     5         :rtype: int
     6         """
     7         size = len(s)
     8         ans = [i for i in range(size)]
     9         p = [[False for i in range(size)] for j in range(size)]
    10         j = 1
    11         while j < size:
    12             i,ans[j] = j - 1,min(ans[j],ans[j - 1] + 1) 
    13             p[j][j] = True
    14             while i >= 0:
    15                 if s[i] == s[j] and ((j - i) < 2 or  p[i+1][j-1]):
    16                     p[i][j] = True
    17                     if i == 0:
    18                         ans[j] = 0
    19                     else:
    20                         ans[j] = min(ans[j],ans[i - 1] + 1)
    21                 i -= 1
    22             j += 1
    23         return ans[size - 1]
    24                     
    25                 
    View Code
  • 相关阅读:
    MFC 控件RadioButton和CheckBox区别
    python的传递实参
    python的返回值
    Machine Learning的定义
    pythion的定义函数和传递实参
    python的用户输入和while循环
    python的字典
    python的if语句
    python的元组及其书写规矩
    python中操作列表
  • 原文地址:https://www.cnblogs.com/chruny/p/5330818.html
Copyright © 2011-2022 走看看