题目如下:

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 = 2
Output: 1
Explanation: 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 = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.

Example 3:

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

Constraints:

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

解题思路:记dp[i][j] = v 表示s[0:j]区间内分割成j段,只需要改变v个字符就可以使得每一段的子串都是回文串。要求dp[i][j]的值,关键就是找出j和j-1的分割点。很显然有dp[i][j] = min(dp[m][j-1] + s[m:j]需要改变的字符的个数),只需要找出最小的分割点m即可。

代码如下:

class Solution(object):
def palindromePartition(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
def calc(substr):
count = 0
for i in range(len(substr)/2):
if substr[i] != substr[len(substr)-i - 1]:count += 1
return count dp = [[float('inf')] * k for _ in s]
dp[0][0] = 0
for i in range(len(s)):
for j in range(k):
if j == 0:
dp[i][j] = calc(s[:i+1])
continue
for m in range(j-1,i):
dp[i][j] = min(dp[i][j],dp[m][j-1] + calc(s[m+1:i+1]))
#print dp
return dp[-1][-1]

最新文章

  1. android view : window
  2. HTML5实现摇一摇
  3. AngularJS 学习之路(1)
  4. sizeof和strlen()区别
  5. Xcode真机调试中&quot;There was an internal API error&quot;错误解决方法
  6. 找出链表中倒数第 k 个结点
  7. MYSQL性能调优: 对聚簇索引和非聚簇索引的认识
  8. Daily Scrum – 1/7
  9. TCP的那些事儿(下)
  10. sqlserver 进行MD5加密
  11. Oracle进程与系统进程
  12. 如何提高 windows 的使用效率?--巧用运行命令
  13. Insert 导致死锁的两种情况
  14. VBoxManage安装
  15. Sharepoint 2010 工作流状态值
  16. MATLAB——sigmoid传递函数
  17. 空间谱专题13:联合解算DOA(ML/AP)
  18. linux文件管理 文件操作
  19. POJ 1597 Function Run Fun
  20. centos7下使用yum安装mysql数据库

热门文章

  1. Golang 无法下载依赖 golang.org (GoLand解决方法)
  2. Redis主从及哨兵
  3. 进阶Java编程(5)基础类库
  4. Vue生命周期及业务场景使用
  5. NSIS MUI 的内置向导页面
  6. Python算法题(一)——青蛙跳台阶
  7. electron-vue在npm run build时报错 ⨯ cannot execute cause=fork/exec C:\Users\801\AppData\Local\electron-builder\Cache\winCodeSign\winCodeSign-2.5.0\rcedit-ia32.exe: Access is denied.
  8. 有关图片上传的相关知识input type=file,HTML5的 input:file上传类型控制
  9. js之语句(条件语句,循环语句,跳转语句)
  10. 基于Openresty+Naxsi的WAF:从小白到实践