LeetCode 1278. Palindrome Partitioning III Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1278. Palindrome Partitioning III

Description

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(n2)).

The time complexity is O(n2 × k), and the space complexity is O(n × (n + k)). Where n is the length of the string s.

PythonJavaC++GoTypeScriptRust
class Solution: def palindromePartition(self, s: str, k: int) -> int: n = len(s) g = [[0] * n for _ in range(n)] for i in range(n - 1, -1, -1): for j in range(i + 1, n): g[i][j] = int(s[i] != s[j]) if i + 1 < j: g[i][j] += g[i + 1][j - 1] f = [[0] * (k + 1) for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, min(i, k) + 1): if j == 1: f[i][j] = g[0][i - 1] else: f[i][j] = inf for h in range(j - 1, i): f[i][j] = min(f[i][j], f[h][j - 1] + g[h][i - 1]) return f[n][k](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !