博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 1278. Palindrome Partitioning III
阅读量:4186 次
发布时间:2019-05-26

本文共 1812 字,大约阅读时间需要 6 分钟。

You are given a string s containing lowercase letters and an integer k. You need to :

  • First, change some characters of s to other lowercase English letters.
  • Then divide s into k non-empty disjoint substrings such that each substring is palindrome.

Return the minimal number of characters that you need to change to divide the string.

 

Example 1:

Input: s = "abc", k = 2Output: 1Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.

Example 2:

Input: s = "aabbc", k = 3Output: 0Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.

Example 3:

Input: s = "leetcode", k = 8Output: 0

 

Constraints:

  • 1 <= k <= s.length <= 100.
  • s only contains lowercase English letters.

Accepted

4,625

Submissions

8,039

---------------------------------------------------------------------------------------------------------------

时间复杂度是O(N^2*k),k是题目中的参数,很难优化下去了。各种边界条件是这个题目的难点:

class Solution:    def palindromePartition(self, s, k):        l = len(s)        cost = [[0 for i in range(l)] for j in range(l)] #        dp = [[l for j in range(k + 2)] for i in range(l)] #[0..i]的字符串分j次最少是多少,i是最后一个元素        for span in range(2, l + 1):            for i in range(0, l + 1 - span):                start, end = i, i + span - 1                same = 0 if s[start] == s[end] else 1                cost[start][end] = cost[start + 1][end - 1] + same        for i in range(l):            dp[i][1] = cost[0][i]            for j in range(2, min(i + 2, k + 2)): #bug1: min(i+1,k+1)                for i0 in range(0, i):                    dp[i][j] = min(dp[i0][j - 1] + cost[i0 + 1][i], dp[i][j])        return dp[l - 1][k]s = Solution()print(s.palindromePartition("abc",2))print(s.palindromePartition("aabbc",3))print(s.palindromePartition("leetcode",8))

 

转载地址:http://ctfoi.baihongyu.com/

你可能感兴趣的文章
在Ubuntu 12.04 64bit上配置,安装和运行go程序
查看>>
ATS程序功能和使用方法详解
查看>>
常用Linux命令总结
查看>>
Tafficserver旁路接入方案综述
查看>>
在CentOS 6.3 64bit上如何从源码生成rpm包?
查看>>
利用lua中的string.gsub来巧妙实现json中字段的正则替换
查看>>
ATS名词术语(待续)
查看>>
ATS缓存相关话题
查看>>
ATS中的RAM缓存简介
查看>>
CDN和Web Cache领域相关的经典书籍推荐
查看>>
在Oracle VM VirtualBox中如何安装64位虚拟机系统
查看>>
安装和使用Oracle VM VirtualBox中的要点,注意事项和遇到的问题
查看>>
ATS上的hosting.config和volume.config文件解读
查看>>
将日志中的指定字段对齐显示输出
查看>>
Linux上chown命令的高级用法
查看>>
利用sort对多字段排序
查看>>
Windows 10完美识别3TB硬盘实录
查看>>
在CentOS 6.x上安装luajit 2.0.4
查看>>
Linux下使用diff和patch制作及打补丁(已经实践可行!)
查看>>
ThinkPad T420更换SSD实录
查看>>