You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:
subtexti is a non-empty string.text (i.e., subtext1 + subtext2 + ... + subtextk == text).subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).Return the largest possible value of k.
Example 1:
Input: text = "ghiabcdefhelloadamhelloabcdefghi" Output: 7 Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
Example 2:
Input: text = "merchant" Output: 1 Explanation: We can split the string on "(merchant)".
Example 3:
Input: text = "antaprezatepzapreanta" Output: 11 Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)".
Constraints:
1 <= text.length <= 1000text consists only of lowercase English characters.This approach uses recursion along with a two-pointer technique. We start by comparing prefixes and suffixes of the string, reducing the problem as we find mirrored chunks and recursively solving the smaller problem for the middle part. This approach takes advantage of the palindrome property (mirrored chunks) to maximize the number of splits.
In the recursive function helper, we compare the prefixes and suffixes of the substring defined by two pointers left and right. If we find a palindrome chunk, we move inward and recursively solve for the center portion. If no chunk is found, the string itself is a palindrome, contributing 1 to the count.
C++
Java
JavaScript
In this approach, we use dynamic programming to optimally determine the number of mirrored chunks. We construct a table where each entry signifies the maximum number of chunks that can be made within a certain substring range. Thus, we fill the table by checking all possible matching starting and ending substring pairs.
A table dp is used where each index i holds the maximum number of mirrored chunks for the substring text[0:i]. For each substring that is itself a palindrome, the table is updated with the maximum possible value of chunk count using previously computed results.
C++
Java
JavaScript
| Approach | Complexity |
|---|---|
| Recursive Approach with Two-Pointer Technique |
|
| Dynamic Programming Approach |
|
Longest Palindromic Substring - Python - Leetcode 5 • NeetCode • 629,130 views views
Watch 9 more video solutions →Practice Longest Chunked Palindrome Decomposition with our built-in code editor and test cases.
Practice on FleetCode