Palindrome Partitioning III Problem
Description
LeetCode Problem 1278.
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 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.sonly contains lowercase English letters.
Solution
Approach: Interval Costs + Partition DP
There are two parts.
The cost of one piece. To make s[i..j] a palindrome with the fewest changes, each pair of mirrored characters s[i + t] and s[j - t] that differ needs exactly one change (set one equal to the other), and pairs that already match need none. So cost[i][j] = (s[i] != s[j]) + cost[i+1][j-1], where a piece of length 1 or 2 has nothing inside. Filling i from right to left makes cost[i+1][j-1] ready when we need it.
The split. Let best[i][j] be the fewest changes to cut the first i characters into j palindromes, with best[0][0] = 0 and every other entry starting as infinity. The last piece is s[h..i-1] for some h, and the first h characters must form j - 1 pieces:
best[i][j] = min over h of best[h][j-1] + cost[h][i-1], for h from j - 1 to i - 1.
The lower bound h >= j - 1 keeps at least one character for each of the earlier pieces, since every piece must be non-empty. The answer is best[n][k].
Complexity: O(n2) to fill cost and O(n2·k) for best, for a string of length n; O(n2 + n·k) space.
class Solution:
def palindromePartition(self, s: str, k: int) -> int:
n = len(s)
# cost[i][j]: changes that make s[i..j] a palindrome
cost = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
cost[i][j] = (s[i] != s[j]) + (cost[i + 1][j - 1] if i + 1 < j else 0)
INF = float('inf')
# best[i][j]: fewest changes to split the first i characters into j palindromes
best = [[INF] * (k + 1) for _ in range(n + 1)]
best[0][0] = 0
for i in range(1, n + 1):
for j in range(1, min(i, k) + 1):
# the last part is s[h..i-1]; the first h characters form j - 1 parts
for h in range(j - 1, i):
best[i][j] = min(best[i][j], best[h][j - 1] + cost[h][i - 1])
return best[n][k]