![]() |
VOOZH | about |
Given a string, the task is to return the length of its longest possible chunked palindrome. It means a palindrome formed by substring in the case when it is not formed by characters of the string. For a better understanding look at the example
Examples:
Input : ghiabcdefhelloadamhelloabcdefghi Output : 7 (ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi) Input : merchant Output : 1 (merchant) Input : antaprezatepzapreanta Output : 11 (a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a) Input : geeksforgeeks Output : 3 (geeks)(for)(geeks)
The entire idea is to create chunks from left and right and recursively.
As you can see, we can match substring from the left side chunk and match it with the exact right side chunk. Once we get a match, we recursively count the length of the longest possible chunked palindrome in the remaining string. We end the recursion once no string is left or when no more valid chunked parts can be found.
Implementation:
V : 1 VOLVO : 3 VOLVOV : 5 ghiabcdefhelloadamhelloabcdefghi : 7 ghiabcdefhelloadamhelloabcdefghik : 1 antaprezatepzapreanta : 11
Following is the C++ implementation with memoization for above problem.
Implementation:
13
Time Complexity: O(N^3), where N is the length of the input string.
Auxiliary Space: O(N^2)