# Problem Statement

Write a program to find the longest palindrome within a given string.

# My Approach

I used Java’s ArrayList collection framework to solve the problem. I iteratively extracted substrings of the given string, and checked if each substring was a palindrome using a separate function. If a substring was determined to be a palindrome, I stored it in the ArrayList. I then sorted the palindromes in the ArrayList using a selection sort algorithm, and printed the longest palindrome.

# Code

class Solution {

public boolean isPalindrome(String check)
{
String sum = " ";
for(int i=check.length()-1;i>=0;i--)
{
sum = sum + check.charAt(i);
}
if(sum.equalsIgnoreCase(check)==true)
{
return true;
}
else
{
return false;
}
}
public String longestPalindrome(String s) {
ArrayList<String> list = new ArrayList<String>();
String sum = " ";
for(int i=0;i<s.length()-1;i++)
{
for(int j=i+1;j<s.length();j++)
{
sum = s.substring(i,j+1);

if(isPalindrome(sum)==true)
{
sum= " ";
}
else
{
sum=" ";
continue;
}
}
}

for(int i = 0;i<list.size()-1;i++)
{
int minIndex=i;
for(int j=i+1;j<list.size();j++)
{
if(list.get(j).length()<list.get(minIndex).length())
{
minIndex=j;
}
}
String temp = list.get(i);
}

if(list.size()!=0)
{

String get = list.get(list.size()-1);
return get;
}
else
{
return null;
}
}
}

The longest palindrome in the given string can be found using the following approach:

class Solution {

public boolean isPalindrome(String check) {
String sum = " ";
for(int i = check.length() - 1; i >= 0; i--) {
sum = sum + check.charAt(i);
}
return sum.equalsIgnoreCase(check);
}

public String longestPalindrome(String s) {
ArrayList<String> list = new ArrayList<String>();
String sum = " ";
for(int i = 0; i < s.length() - 1; i++) {
for(int j = i + 1; j < s.length(); j++) {
sum = s.substring(i, j + 1);
if(isPalindrome(sum)) {
sum = " ";
} else {
sum = " ";
continue;
}
}
}

for(int i = 0; i < list.size() - 1; i++) {
int minIndex = i;
for(int j = i + 1; j < list.size(); j++) {
if(list.get(j).length() < list.get(minIndex).length()) {
minIndex = j;
}
}
String temp = list.get(i);
list.set(i, list.get(minIndex));
list.set(minIndex, temp);
}

if(list.size() != 0) {
return list.get(list.size() - 1);
} else {
return null;
}
}
}

This program will find the longest palindrome within the given string.