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
intok
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.
暴力DFS+Memo
class Solution(object):
def palindromePartition(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
INF = 99999999
memo={}
def count(s):
return len([i for i in range(len(s) // 2) if s[i] != s[-i - 1]])
def dfs(s,k):
if k==1: return count(s)
if (s,k) in memo: return memo[(s,k)]
res = INF
for i in range(len(s)-k+1):
res=min(res, count(s[:i+1])+dfs(s[i+1:],k-1))
memo[(s,k)]=res
return res
return dfs(s,k)
s=Solution()
print(s.palindromePartition(s = "abc", k = 2))
print(s.palindromePartition(s = "aabbc", k = 3))
print(s.palindromePartition(s = "leetcode", k = 8))