Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficiently determine the longest individual character palindrome in a given string?

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 JOHNOLSON. 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.

like image 628
jbranchaud Avatar asked Nov 20 '11 18:11

jbranchaud


People also ask

How do you find the length of the longest palindrome in a string?

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.

Which method is more efficient to find all palindrome in a string?

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.

What is the length of the longest palindromic substring?

The largest known palindromic word is saippuakivikauppias (19 letters), which is Finnish for a dealer in lye (caustic soda).


1 Answers

You can do it in linear time, it's described here with a code sample.

like image 133
Jordan Bentley Avatar answered Sep 29 '22 19:09

Jordan Bentley