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 a 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.
Solutions
Solution 1: Dynamic Programming
We define \(f[i][j]\) to represent the minimum number of changes needed to partition the first \(i\) characters of the string \(s\) into \(j\) palindromic substrings. We assume the index \(i\) starts from 1, and the answer is \(f[n][k]\).
For \(f[i][j]\), we can enumerate the position \(h\) of the last character of the \((j-1)\)-th palindromic substring. Then \(f[i][j]\) is equal to the minimum value of \(f[h][j-1] + g[h][i-1]\), where \(g[h][i-1]\) represents the minimum number of changes needed to turn the substring \(s[h..i-1]\) into a palindrome (this part can be preprocessed with a time complexity of \(O(n^2)\)).
The time complexity is \(O(n^2 \times k)\), and the space complexity is \(O(n \times (n + k))\). Where \(n\) is the length of the string \(s\).