Longest Palindrome Substring in a String in Java With Examples

Longest palindrome substring in a string is a very common java interview question. To find out the longest palindrome in String, first of all, we need to identify the logic to do it.

Longest Palindrome Substring in a String Algorithm

The key point here is that from the mid of any palindrome string if we go to the right and left by 1 place, itโ€™s always the same character.

For example 12321, here mid is 3 and if we keep moving one position on both sides, we get 2 and then 1. We will use the same logic in our java program to find out the longest palindrome.

However, if the palindrome length is even, the mid-size is also even. So we need to make sure in our program that this is also checked. For example, 12333321, here mid is 33 and if we keep moving one position in both sides, we get 3, 2 and 1.

Longest Palindrome Substring in a String Java Program

In our java program, we will iterate over the input string with mid as 1st place and check the right and left character.

We will have two global variables to save the start and the end position for palindrome. We also need to check if there is already a longer palindrome found since there can we multiple palindromes in the given string.

Here is the final program that works fine for all the cases.

Below image shows the output of the above longest palindrome java program.

longest-palindrome-in-a-string-java

We can improve the above code by moving the palindrome and longest lengths check into a different function. However, I have left that part for you. ๐Ÿ™‚

Please let me know if there are any other better implementations or if it fails in any case.

By admin

Leave a Reply

%d bloggers like this: