You are given a string s containing lowercase letters and an integer k. You need to :
- First, change some characters of
sto other lowercase English letters. - Then divide
sintoknon-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.sonly 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))

本文探讨了一道算法题目,旨在寻找将给定字符串分割为k个回文子串所需的最小字符更改数。通过动态规划算法,文章详细解释了如何高效地解决这一问题,并提供了具体的代码实现。
641

被折叠的 条评论
为什么被折叠?



