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 <= 2000
s
consists only of lowercase English letters.This problem asks whether a given string s
can be partitioned into three non-empty palindromic substrings. The solution uses dynamic programming to efficiently determine if substrings are palindromes.
Approach:
Palindrome Check: The core idea is to efficiently determine if any substring of s
is a palindrome. We use a boolean matrix g
where g[i][j]
is true
if the substring s[i...j]
(inclusive) is a palindrome, and false
otherwise. This is filled using dynamic programming:
i == j
) are always palindromes (g[i][i] = true
).g[i][j]
is true if and only if:
s[i] == s[j]
(the first and last characters are equal), andg[i+1][j-1]
is true (the inner substring is also a palindrome).Three-Partition Check: Once the g
matrix is built, we iterate through all possible partitions of s
into three substrings. For each partition at indices i
and j
, we check if all three substrings s[0...i]
, s[i+1...j]
, and s[j+1...n-1]
are palindromes using the g
matrix. If we find such a partition, we immediately return true
.
Result: If no such three-palindrome partition is found after checking all possibilities, we return false
.
Time Complexity Analysis:
g
matrix takes O(n^2) time, where n is the length of the string. This is because we iterate over all possible substring starting and ending indices.i
and j
values.Therefore, the overall time complexity is O(n^2).
Space Complexity Analysis:
The space complexity is dominated by the g
matrix, which has dimensions n x n. Hence, the space complexity is O(n^2).
Code Explanation (Python):
class Solution:
def checkPartitioning(self, s: str) -> bool:
n = len(s)
g = [[True] * n for _ in range(n)] # Initialize g matrix
# Build the g matrix using dynamic programming
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
g[i][j] = s[i] == s[j] and (i + 1 == j or g[i + 1][j - 1])
# Check for three-palindrome partitions
for i in range(n - 2):
for j in range(i + 1, n - 1):
if g[0][i] and g[i + 1][j] and g[j + 1][-1]: # Check if all three substrings are palindromes
return True
return False # No three-palindrome partition found
The code in other languages (Java, C++, Go) follows the same algorithm and has the same time and space complexities. The only difference is the syntax and data structure usage specific to each language.