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 a palindrome.
Return the minimal number of characters that you need to change to divide the string.
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.
Input: s = "aabbc", k = 3 Output: 0 Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
Input: s = "leetcode", k = 8 Output: 0
1 <= k <= s.length <= 100
.s
only contains lowercase English letters.
from functools import cache
class Solution:
def palindromePartition(self, s: str, k: int) -> int:
@cache
def palindromeChange(i: int, j: int) -> int:
if i >= j:
return 0
return palindromeChange(i + 1, j - 1) + (s[i] != s[j])
@cache
def subPartition(i: int, k: int) -> int:
if k == 1:
return palindromeChange(i, len(s) - 1)
return min(palindromeChange(i, j) + subPartition(j + 1, k - 1) for j in range(i, len(s) - k + 1))
return subPartition(0, k)