# 1278. Palindrome Partitioning III

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.

``````class Solution {
public:
int palindromePartition(string s, int k) {
int n = s.size();
vector<vector<int>> pd(n, vector<int>(n)), dp(k + 1, vector<int>(n));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
pd[i][j] = getChanges(s, i, j);
}
}
for (int i = 0; i < n; ++i) {
dp[1][i] = pd[0][i];
}
for (int i = 2; i <= k; ++i) {
for (int end = i - 1; end < n; ++end) {
dp[i][end] = n;
for (int start = end - 1; start >= i - 2; --start) {
dp[i][end] = min(dp[i][end], dp[i - 1][start] + pd[start + 1][end]);
}
}
}
return dp[k][n - 1];
}
int getChanges(string s, int start, int end) {
int res = 0;
while (start < end) {
if (s[start++] != s[end--]) ++res;
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/CHANGE_ME

Palindrome Partitioning IV

Palindrome Partitioning II

Palindrome Partitioning

https://leetcode.com/problems/palindrome-partitioning-iii/

https://leetcode.com/problems/palindrome-partitioning-iii/discuss/498677/Step-by-Step-solution-DP-(Java)

https://leetcode.com/problems/palindrome-partitioning-iii/discuss/442083/Simple-C%2B%2B-Dp-O(N2K)-Beats-100-with-Explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation