|
| 1 | +# 1278. Palindrome Partitioning III |
| 2 | +You are given a string `s` containing lowercase letters and an integer `k`. You need to : |
| 3 | +* First, change some characters of `s` to other lowercase English letters. |
| 4 | +* Then divide `s` into `k` non-empty disjoint substrings such that each substring is a palindrome. |
| 5 | + |
| 6 | +Return *the minimal number of characters that you need to change to divide the string*. |
| 7 | + |
| 8 | +#### Example 1: |
| 9 | +<pre> |
| 10 | +<strong>Input:</strong> s = "abc", k = 2 |
| 11 | +<strong>Output:</strong> 1 |
| 12 | +<strong>Explanation:</strong> You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome. |
| 13 | +</pre> |
| 14 | + |
| 15 | +#### Example 2: |
| 16 | +<pre> |
| 17 | +<strong>Input:</strong> s = "aabbc", k = 3 |
| 18 | +<strong>Output:</strong> 0 |
| 19 | +<strong>Explanation:</strong> You can split the string into "aa", "bb" and "c", all of them are palindrome. |
| 20 | +</pre> |
| 21 | + |
| 22 | +#### Example 3: |
| 23 | +<pre> |
| 24 | +<strong>Input:</strong> s = "leetcode", k = 8 |
| 25 | +<strong>Output:</strong> 0 |
| 26 | +</pre> |
| 27 | + |
| 28 | +#### Constraints: |
| 29 | +* `1 <= k <= s.length <= 100`. |
| 30 | +* `s` only contains lowercase English letters. |
| 31 | + |
| 32 | +## Solutions (Python) |
| 33 | + |
| 34 | +### 1. Solution |
| 35 | +```Python |
| 36 | +from functools import cache |
| 37 | + |
| 38 | + |
| 39 | +class Solution: |
| 40 | + def palindromePartition(self, s: str, k: int) -> int: |
| 41 | + @cache |
| 42 | + def palindromeChange(i: int, j: int) -> int: |
| 43 | + if i >= j: |
| 44 | + return 0 |
| 45 | + |
| 46 | + return palindromeChange(i + 1, j - 1) + (s[i] != s[j]) |
| 47 | + |
| 48 | + @cache |
| 49 | + def subPartition(i: int, k: int) -> int: |
| 50 | + if k == 1: |
| 51 | + return palindromeChange(i, len(s) - 1) |
| 52 | + |
| 53 | + return min(palindromeChange(i, j) + subPartition(j + 1, k - 1) for j in range(i, len(s) - k + 1)) |
| 54 | + |
| 55 | + return subPartition(0, k) |
| 56 | +``` |
0 commit comments