How to find the Longest Palindrome String in Java ?



How to find the Longest Palindrome String in Java ?

  • A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, example as madam.
  • Write a java program to find the longest palindrome present in a given string.
 Longest Palindrome in a String

Longest Palindrome in a String Using Java

  • The string can be of odd or even length and hence the findLongestPalindromeWithSpecifiedParameter() is called twice for each string.
  • In the method, findLongestPalindromeWithSpecifiedParameter() left will decrement and move towards the start of the string until it reaches start and then right will increment and move towards the end of the string until it reaches the end.
  • And any left and right reach destination (i.e. start and end respectively)at any point then the method will return.

Sample Code

import java.io.*;


public class LongestPalindromeExample {

    public String findTheLongestPalindrome(String str){
        if (str == null) {
            return null;
        }
        String longestPalindrome = String.valueOf(str.charAt(0));
        for (int i = 0; i < str.length() - 1; i++) {
            String returnedPalindrome = findLongestPalindromeWithSpecifiedParameter(str, i, i);
            if (returnedPalindrome.length() > longestPalindrome.length()) {
                longestPalindrome = returnedPalindrome;
            }
            returnedPalindrome = findLongestPalindromeWithSpecifiedParameter(str, i, i + 1);
            if (returnedPalindrome.length() > longestPalindrome.length()) {
                longestPalindrome = returnedPalindrome;
            }
        }
        return longestPalindrome;
    }

    public String findLongestPalindromeWithSpecifiedParameter(String str, int left, int right) {
        if (left > right)
            return null;

        while (left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)) {
            left--;
            right++;
        }
        return str.substring(left + 1, right);
    }

    public static void main(String[] args){
        LongestPalindromeExample longestPalindrome1 = new LongestPalindromeExample();
        System.out.println("Longest palindrome in abcmadamcbamadam is " + longestPalindrome1.findTheLongestPalindrome("abcmadamcbamadam"));
        System.out.println("Longest palindrome in abcba is " + longestPalindrome1.findTheLongestPalindrome("abcba"));
    }
}

Output

Longest palindrome in abcmadamcbamadam is abcmadamcba
Longest palindrome in abcba is abcba

Related Searches to How to find the Longest Palindrome String in Java ?