Given a string of length N containing characters [A-Z], how do I determine the longest palindrome for an individual character?
I will illustrate this with an example:
Given string: JOHNOLSON
In analyzing the string, we find that we have a palindrome with the character O
such that the string looks like J
O
HN
O
LS
O
N
. The palindrome for the O
's is of length 7 essentially looking like O
--
O
--
O
. Also, notice that there is a palindrome with N
, but it is only of length 6.
Another example,
Given string: ABCJOHNOLSON
gives the same result as above with a palindrome of the O
's of length 7 looking like O
--
O
--
O
.
However, with the given string ABCJOHNOLSONDA
, the longest individual character palindrome is of length 14 with the character A
looking like A
------------
A
.
Other simple examples include:
ABA
--> A
-
A
(length 3)
ABAXYZ
--> A
-
A
(length 3)
ABAXYZA
--> A
---
A
(length 5), not length 7 because A
-
A
---
A
is not a palindrome for the letter A
.
Pay special attention to the last example because it illustrates one of the subtle nuances of the problem.
Naive Approach: The simplest approach to solve the problem is to generate all possible substrings of the given string and print the length of the longest substring which is a palindrome.
4. Manacher's Algorithm. Manacher's algorithm finds the longest palindromic substring in linear time. We'll use this algorithm to find all substrings that are palindromes.
The largest known palindromic word is saippuakivikauppias (19 letters), which is Finnish for a dealer in lye (caustic soda).
You can do it in linear time, it's described here with a code sample.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With