Palindrome Partitioning IV — LeetCode 1745 Python Solution
- Problem
- #1745
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false. A string is said to be palindrome if it the same string when reversed.
Example
- Input
- s = "abcbdd"
- Output
- true
- Explanation
- "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.
Python solution
class Solution:
def checkPartitioning(self, s: str) -> bool:
n = len(s)
f = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
f[i][j] = s[i] == s[j] and (i + 1 == j or f[i + 1][j - 1])
for i in range(n - 2):
for j in range(i + 1, n - 1):
if f[0][i] and f[i + 1][j] and f[j + 1][-1]:
return True
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1745. Palindrome Partitioning IV 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 1745. Palindrome Partitioning IV?
- LeetCode 1745. Palindrome Partitioning IV is rated Hard on LeetCode.
- What topics does LeetCode 1745. Palindrome Partitioning IV cover?
- LeetCode 1745. Palindrome Partitioning IV is tagged String and Dynamic Programming on LeetCode.