Java Program to Find Longest Palindrome in The Given String

In this post we’ll see a Java program to find the longest palindrome in the given string. In the given string there may be more than one palindromes but you need to find which one is the longest and display that one.

For finding the longest palindrome in the string you need to start from the middle of the string and move both left and right by one character and compare those characters, if those two character are equal that means you have a palindrome and you do the same thing for the next two characters. As example in string “98189” center is 1 and by moving both left and right and comparing you can see that 8 and 8 and then 9 and 9 are equal. At the same time center of the String also moves in the program as you have to find the longest palindrome in the String.

Another thing to consider is the case when String is even, in that case you will be taking two characters as center and then do the comparison of characters. The two characters considered as center should also be equal.

Java program to find the longest palindrome

Output

The time complexity of this solution is O(N2) and space complexity is O(1) as the same string is used and memory requirement in the program doesn’t increase.

That’s all for the topic Java Program to Find Longest Palindrome in The Given String. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.