Palindrome Partitioning IV Problem
Description
LeetCode Problem 1745.
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 1:
Input: s = "abcbdd"
Output: true
Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.
Example 2:
Input: s = "bcbddxy"
Output: false
Explanation: s cannot be split into 3 palindromes.
Constraints:
3 <= s.length <= 2000sconsists only of lowercase English letters.
Solution
Approach: Palindrome Table, Then Try Every Split
First build a table f[i][j] that says whether s[i..j] is a palindrome. A substring is a palindrome when its end characters match and the part between them is a palindrome (or is empty or a single character). Filling the table with i going down from the end makes the inner entry f[i + 1][j - 1] ready when it is needed.
Then try every way to cut the string into three non-empty parts: the first ends at i, the second ends at j, and the third is the rest. If f[0][i], f[i + 1][j] and f[j + 1][n - 1] are all true, the answer is true. If no cut works, the answer is false.
Complexity: O(n2) time and O(n2) space for the table, where n is the length of s.
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 False