Palindrome Partitioning III — LeetCode 1278 Python Solution
- Problem
- #1278
- Pattern
- Dynamic Programming
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
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]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times k) |
| Space | O(n \times (n + k)) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1278. Palindrome Partitioning III is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1278. Palindrome Partitioning III?
- LeetCode 1278. Palindrome Partitioning III is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1278. Palindrome Partitioning III?
- The Python solution on this page runs in O(n^2 \times k).
- What is the space complexity of LeetCode 1278. Palindrome Partitioning III?
- The Python solution on this page uses O(n \times (n + k)) auxiliary space.
- What topics does LeetCode 1278. Palindrome Partitioning III cover?
- LeetCode 1278. Palindrome Partitioning III is tagged String and Dynamic Programming on LeetCode.