Sunday, 13 August 2017

Write a program to find out the longest palindrome of a given String in JAVA

This is very tricky java interview questions. This question has been asked  in almost every product based company.

This problem can be asked in different ways like "find out no of palindromes of a given String"

Logic is pretty simple here. We will check every substring from start and end index. If the substring is palindrome then store it somewhere and check other substrings as well.

 So if the given input is "abcdcbaaaaaabccccba", then longest palindrome would be "cbaaaaaabc"

Sample Code:

/**
 * 
 * @author Sourin
 * 
 * This class is used to find out the longest palindrome of a given string. Logic is pretty simple, everytime 
 * we will pull out start and end index and check that is palindrome or not, if its palindrome store it somewhere and check the other substrings.
 *
 */
public class LongestPalindrome {
public static void main(String[] args) {
String palindrome="abcdcbaaaaaabccccba";
String longestPalindrome2=checkLongestPalindrome(palindrome);
System.out.println("Longest Palindrome is: "+ longestPalindrome2);
}
public static String checkLongestPalindrome(String palindrome)
{
String longestPalindrome="";
for(int i=0;i<palindrome.length();i++)
{
for(int j=palindrome.length()-1;j!=i;j--)
{
if(isPalindrome(palindrome.substring(i,j+1)))//check whether given string is palindrome or not.
{
if(palindrome.substring(i,j+1).length()>longestPalindrome.length())
{
longestPalindrome=palindrome.substring(i,j+1);
}
}
}
}
return longestPalindrome;
}
public static boolean isPalindrome(String ptest)
{
int k=ptest.length()-1;
for(int i=0;i<ptest.length()/2;i++)
{
if(ptest.charAt(i)!=ptest.charAt(k)){
return false;
}
k--;
}
return true;
}

}


Sample Output:


Longest Palindrome is: cbaaaaaabc





2 comments:

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...